Struts2(二)---將頁面表單中的數據提交給Action


問題:在struts2框架下,如何將表單數據傳遞給業務控制器Action。

struts2中,表單想Action傳遞參數的方式有兩種,並且這兩種傳參方式都是struts2默認實現的,他們分別是基本屬性注入、域模型注入

、其中:

---基本屬性注入,是將表單的數據項分別傳入給Action中的一些基本基本類型。

---域模型注入,是將表單的數據項打包傳入給Action中的一個實體對象。

我們項目Struts2的實例,在其基礎上使用這2中方式完成頁面向Action的參數傳遞。具體的我們可以在項目首頁regist.jsp上追加表單,

並在表單中模擬一些數據,將這些數據提交給RegistAction,最后在RegistAction中將接受的參數輸出到控制台。

具體實現步驟:

1>基本屬性注入

步驟一:

在項目的regist.jsp中,追加表單,並將該表單設置提交給RegistAction,即將form的action屬性設置為:

<form action="regist" method="post">

在表單中增加一個文本框,用於輸入一個公司姓名,該文本框的name屬性值為company。代碼如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page contentType="text/html;charset=gbk"%> 
<%@ taglib prefix="s" uri="/struts-tags" %>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    
    <title>京東商城注冊頁面</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <%
        request.setCharacterEncoding("gbk");
     %>
  </head>
  
  <body>
           <center>
               <form action="regist" method="post">&nbsp;&nbsp;司: <input type="text" name="company"/> <br>
                   <table>
                    <tr>
                        <td><input type="submit" value="注冊"/></td>
                        <td><input type="reset" value="重置" ></td>
                    </tr>
                </table>
               </form>
            <s:fielderror />
           </center>
  </body>
</html>

 

步驟二:RegistAction中,接收表單傳入的參數

在RegistAction中,追加屬性並用於接收表單傳入的姓名參數,該屬性的名稱要求與文本框的值相同(company),並且該屬性需要

具備set方法。在業務方法中輸出屬性company的值。通知為了方便觀察代碼執行的順序,在Action默認構造器中,輸出任意的文字,

代碼如下:

 

package com.wss.action;

import com.opensymphony.xwork2.ActionSupport;
import com.wss.Dao.School;
import com.wss.Dao.User;
import com.wss.Dao.UserDao;

public class RegistAction extends ActionSupport{

    public RegistAction()
    {
        System.out.println("Initialization RegistAction....");
    }
private String company;
    public void setCompany(String company)
    {
        System.out.println("Setting the company");
        this.company=company;        
    }
    public String execute() throws Exception{
        UserDao ud =new UserDao();
        
        System.out.println("The company is "+this.company);
       //if(ud.regist(user)!=0){
        
            this.addFieldError("success", "注冊成功");
            return SUCCESS;
        //}
        //this.addFieldError("error", "注冊失敗");
        //return ERROR;
        
    }
        
    
}

 

步驟三:測試

重新部署該項目並啟動tomcat,打開瀏覽器,針對當前的案例,在地址欄中輸入地址:

http://localhost:8080/ShopDemo/regist.jsp

運行結果:

 

點擊提交:

Eclipse控制台輸出:

Initialization RegistAction....
Setting the company

The company is 公司

控制台輸出的順序可以證明代碼的執行順序:實例化Action--->調用set方法注入參數company的值-->調用業務方法execute(),

當然這個過程是Struts2的API自行實現的,我們只需要在寫代碼時滿足上述步驟中的要求即可。

 

2>域模型注入一(Action中屬性用private User user =new User();已創建)

 

步驟一:修改表單,追加演示數據

在regist.jsp修改表單,追加用戶名、密碼、電話和地址四個文本框,模擬輸入用戶的相關信息,代碼如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page contentType="text/html;charset=gbk"%> 
<%@ taglib prefix="s" uri="/struts-tags" %>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    
    <title>京東商城注冊頁面</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <%
        request.setCharacterEncoding("gbk");
     %>
  </head>
  
  <body>
           <center>
               <form action="regist" method="post">
               
                   用戶名:<input type="text" name="user.name"/><br>&nbsp;&nbsp;碼:<input type="password" name="user.password"/><br>&nbsp;&nbsp;機:<input type="text" name="user.phone" /><br>&nbsp;&nbsp;址:<input type="text" name="user.address"/><br>&nbsp;&nbsp;司: <input type="text" name="company"/> <br>
                   
                   <table>
                    <tr>
                        <td><input type="submit" value="注冊"/></td>
                        <td><input type="reset" value="重置" ></td>
                    </tr>
                </table>
               </form>
            <s:fielderror />
           </center>
  </body>
</html>

 

步驟二:創建實體類

 

創建包com.wss.Dao,用於存放實體類。在com.wss.Dao包下創建實體類User,用於封裝表單中追加的數據,即用戶名、密碼、

電話和地址。User中要包含兩個屬性,用於封裝用戶名、密碼電話和地址,並給屬性提供get和set方法,代碼如下:

 

package com.wss.Dao;

public class User {
    private int id;
    private String name;
    private String password;
    private String phone;
    private String address;

    public User()
    {
        System.out.println("Initialization the User......");
    }
    public int getId() {
        System.out.println("Getting the ID");
        return id;
    }

    public void setId(int id) {
        System.out.println("Setting the ID");
        this.id = id;
    }

    public String getName() {
        System.out.println("Getting the name");
        return name;
    }

    public void setName(String name) {
        System.out.println("Setting the name");
        this.name = name;
    }

    public String getPassword() {
        System.out.println("Getting the password");
        return password;
    }

    public void setPassword(String password) {
        System.out.println("Setting the password");
        this.password = password;
    }

    public String getPhone() {
        System.out.println("Getting the phone");
        return phone;
    }

    public void setPhone(String phone) {
        System.out.println("Setting the phone");
        this.phone = phone;
    }

    public String getAddress() {
        System.out.println("Getting the address");
        return address;
    }

    public void setAddress(String address) {
        System.out.println("Setting the address");
        this.address = address;
    }

}

 

步驟三:修改RegistAction,接受表單傳入的參數

在RegistAction中,追加屬性用於接受表單傳入的用戶名、密碼、電話和地址參數,該屬性的類型為User類型,名稱為user,並為

該屬性提供get和set方法。

在業務方法(execute())中輸出屬性user的值,代碼如下:

 

package com.wss.action;

import com.opensymphony.xwork2.ActionSupport;
import com.wss.Dao.School;
import com.wss.Dao.User;
import com.wss.Dao.UserDao;

public class RegistAction extends ActionSupport{

    public RegistAction()
    {
        System.out.println("Initialization RegistAction....");
    }
    
    private User user =new User();
    //private User user;
    public User getUser() {
        System.out.println("Getting the getUser");
        return user;
    }

    public void setUser(User user) {
        System.out.println("Setting the setUser");
        this.user = user;
    }private String company;
    public void setCompany(String company)
    {
        System.out.println("Setting the company");
        this.company=company;        
    }
    
    
    public String execute() throws Exception{
        UserDao ud =new UserDao();
        
        System.out.println("The company is "+this.company+" The name is "+this.user.getName()+" The phone is "+this.user.getAddress());
       //if(ud.regist(user)!=0){
        
            this.addFieldError("success", "注冊成功");
            return SUCCESS;
        //}
        //this.addFieldError("error", "注冊失敗");
        //return ERROR;
        
    }
        
    
}

 

步驟四:修改表單,設置文本框屬性

在regist.jsp中,修改表單新增的4個文本框name屬性值。對於域模型注入的方式,文本框name屬性值應該是具有"對象名.屬性名"

格式的表達式。

其中對象名指的是Action中的實體類型屬性名,即User對象實例,屬性名指的是實體類型中的屬性名

(name,password,phone,address),代碼如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page contentType="text/html;charset=gbk"%> 
<%@ taglib prefix="s" uri="/struts-tags" %>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    
    <title>京東商城注冊頁面</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <%
        request.setCharacterEncoding("gbk");
     %>
  </head>
  
  <body>
           <center>
               <form action="regist" method="post">
               
                   用戶名:<input type="text" name="user.name"/><br>&nbsp;&nbsp;碼:<input type="password" name="user.password"/><br>&nbsp;&nbsp;機:<input type="text" name="user.phone" /><br>&nbsp;&nbsp;址:<input type="text" name="user.address"/><br>&nbsp;&nbsp;司: <input type="text" name="company"/> <br>
                   
                   <table>
                    <tr>
                        <td><input type="submit" value="注冊"/></td>
                        <td><input type="reset" value="重置" ></td>
                    </tr>
                </table>
               </form>
            <s:fielderror />
           </center>
  </body>
</html>

 

步驟五:測試

重新部署項目並啟動tomcat,在瀏覽器中輸入地址:http://localhost:8080/ShopDemo/regist.jsp

效果如下圖所示(當然為了稍候測試方便,我自己輸入了一些信息):

 

 點擊提交,查看myeclipse的控制台,輸出結果如下:

 

Initialization the User......
Initialization RegistAction....
Setting the company
Getting the getUser
Setting the name
Getting the getUser
Setting the password
Getting the getUser
Setting the phone
Getting the name
Getting the address
The company is 公司 The name is good The phone is 111

控制台輸出的順序可以證明代碼的執行順序為:實例化Action-->實例化User並注入參數-->調用set方法注入User對象-->調用業務

方法。

但這個時候是先實例化User對象,再實例化Action對象,主要是因為Action中有private User user =new User();創建實例對象前,一般會對靜態屬性、靜態對碼段,對象屬性按順序進行初始化后,才調用Action的構造函數;user實例化后(我自己感覺實例化后並

把user對象注入了,即相當於調用了setUser方法);

再接着

Getting the getUser
Setting the name
Getting the getUser
Setting the password
Getting the getUser
Setting the phone
Getting the name
Getting the address
用於調用set方法注入user對象各屬性。

 

3>域模型注入二(Action中屬性 private School school;沒有用new創建對象)

 

步驟一:修改表單,追加演示數據

在regist.jsp修改表單,追加用學校、城市、院系三個文本框,模擬輸入用戶的相關信息,代碼如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page contentType="text/html;charset=gbk"%> 
<%@ taglib prefix="s" uri="/struts-tags" %>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    
    <title>京東商城注冊頁面</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <%
        request.setCharacterEncoding("gbk");
     %>
  </head>
  
  <body>
           <center>
               <form action="regist" method="post">
               
                   用戶名:<input type="text" name="user.name"/><br>&nbsp;&nbsp;碼:<input type="password" name="user.password"/><br>&nbsp;&nbsp;機:<input type="text" name="user.phone" /><br>&nbsp;&nbsp;址:<input type="text" name="user.address"/><br>&nbsp;&nbsp;司: <input type="text" name="company"/> <br>&nbsp;&nbsp;校:<input type="text" name="school.name"/>&nbsp;&nbsp;市:<input type="text" name="school.city" />&nbsp;&nbsp;系:<input type="text" name="school.department" />
                   
                   <table>
                    <tr>
                        <td><input type="submit" value="注冊"/></td>
                        <td><input type="reset" value="重置" ></td>
                    </tr>
                </table>
               </form>
            <s:fielderror />
           </center>
  </body>
</html>

 

步驟二:創建實體類

創建包com.wss.Dao,用於存放實體類。在com.wss.Dao包下創建實體類School,用於封裝表單中追加的數據,即學校、城市和

院系。

School中要包含三個屬性,用於封裝學校、城市和院系,並給屬性提供get和set方法,代碼如下:

 

package com.wss.Dao;

public class School {

    private String name;
    private String city;
    private String department;
    
    public School()
    {
        System.out.println("Initilization School....");
    }
    public String getName() {
        System.out.println("Getting the school name");
        return name;
    }
    public void setName(String name) {
        System.out.println("Setting the school name");
        this.name = name;
    }
    public String getCity() {
        System.out.println("Getting the school city");
        return city;
    }
    public void setCity(String city) {
        System.out.println("Setting the school city");
        this.city = city;
    }
    public String getDepartment() {
        System.out.println("Getting the school department");
        return department;
    }
    public void setDepartment(String department) {
        System.out.println("Setting the school department");
        this.department = department;
    }
    
    
}

 

步驟三:修改RegistAction,接受表單傳入的參數

 

在RegistAction中,追加屬性用於接受表單傳入的學校、城市和院系,該屬性的類型為School類型,名稱為school,

並為該屬性提供get和set方法。

在業務方法(execute())中輸出屬性school的值,代碼如下:

 

package com.wss.action;

import com.opensymphony.xwork2.ActionSupport;
import com.wss.Dao.School;
import com.wss.Dao.User;
import com.wss.Dao.UserDao;

public class RegistAction extends ActionSupport{

    public RegistAction()
    {
        System.out.println("Initialization RegistAction....");
    }
    
    private User user =new User();
    //private User user;
    public User getUser() {
        System.out.println("Getting the getUser");
        return user;
    }

    public void setUser(User user) {
        System.out.println("Setting the setUser");
        this.user = user;
    }
    
    private School school;
    
    public School getSchool() {
        System.out.println("Getting the getSchool");
        return school;
    }

    public void setSchool(School school) {
        System.out.println("Setting the setSchool");
        this.school = school;
    }

    private String company;
    public void setCompany(String company)
    {
        System.out.println("Setting the company");
        this.company=company;        
    }
    
    
    public String execute() throws Exception{
        UserDao ud =new UserDao();
        
        System.out.println("The company is "+this.company+" The name is "+this.user.getName()+" The phone is "+this.user.getAddress());
        System.out.println("The school name is "+this.school.getName()+" The city is "+this.school.getCity()+" The department is "+ this.school.getDepartment());
        
        //if(ud.regist(user)!=0){
        
            this.addFieldError("success", "注冊成功");
            return SUCCESS;
        //}
        //this.addFieldError("error", "注冊失敗");
        //return ERROR;
        
    }
        
    
}

 

步驟四:修改表單,設置文本框屬性

在regist.jsp中,修改表單新增的3個文本框name屬性值。對於域模型注入的方式,文本框name屬性值應該是具有"對象名.屬性名"

格式的表達式。

其中對象名指的是Action中的實體類型屬性名school,屬性名指的是實體類型中的各屬性名(name,city,department),

代碼如下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ page contentType="text/html;charset=gbk"%> 
<%@ taglib prefix="s" uri="/struts-tags" %>


<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    
    <title>京東商城注冊頁面</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <%
        request.setCharacterEncoding("gbk");
     %>
  </head>
  
  <body>
           <center>
               <form action="regist" method="post">
               
                   用戶名:<input type="text" name="user.name"/><br>&nbsp;&nbsp;碼:<input type="password" name="user.password"/><br>&nbsp;&nbsp;機:<input type="text" name="user.phone" /><br>&nbsp;&nbsp;址:<input type="text" name="user.address"/><br>&nbsp;&nbsp;司: <input type="text" name="company"/> <br>&nbsp;&nbsp;校:<input type="text" name="school.name"/>&nbsp;&nbsp;市:<input type="text" name="school.city" />&nbsp;&nbsp;系:<input type="text" name="school.department" />
                   
                   <table>
                    <tr>
                        <td><input type="submit" value="注冊"/></td>
                        <td><input type="reset" value="重置" ></td>
                    </tr>
                </table>
               </form>
            <s:fielderror />
           </center>
  </body>
</html>

 

步驟五:測試

重新部署項目並啟動tomcat,在瀏覽器中輸入地址:http://localhost:8080/ShopDemo/regist.jsp

效果如下圖所示(當然為了稍候測試方便,我自己輸入了一些信息):

 

 點擊提交,查看myeclipse的控制台,輸出結果如下:

Initialization the User......
Initialization RegistAction....
Setting the company
Getting the getSchool
Initilization School....
Setting the setSchool
Setting the school city
Getting the getSchool
Setting the school department
Getting the getSchool
Setting the school name
Getting the getUser
Setting the address
Getting the getUser
Setting the name
Getting the getUser
Setting the password
Getting the getUser
Setting the phone
Getting the name
Getting the address
The company is 公司 The name is good The phone is wrwer
Getting the school name
Getting the school city
Getting the school department
The school name is xuexiao The city is beiijng The department is shuxue

 控制台輸出的順序可以證明代碼的執行順序為:實例化Action-->實例化User並注入參數-->調用set方法注入User對象-->調用業務

方法。

在這里,private User user =new User();和private School school;不一樣,school只是一個引用,並沒有用new創建出對象,

所以在對school的各屬性name、city和department用set方法注入時,用getSchool方法得到school對象時(Getting the getSchool),還沒有school對象的存在,此時調用School的構造函數進行初始化創建school對象;然后通過school對象對其各

屬性用setName....方法對school的各屬性進行注入。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM