1. 程式人生 > >Struts2獲取表單資料的方式

Struts2獲取表單資料的方式

有四種方式可以獲取jsp表單提交的資料:

第一種:定義屬性值,通過Setters方法獲取

    <form action="user/LoginAction.html" method="post"> 
        賬號: <input type="text" name="userName"><br>
        密碼: <input type="text" name="passWord"><br>
        <input type="submit" value="提交">
    </form>
public class UserAction {

    private String userName;
    private String passWord;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public
void setPassWord(String passWord) { this.passWord = passWord; } }

第二種:從ServletActionContext中獲取request物件,再從request物件中獲取引數

    <form action="user/LoginAction.html" method="post"> 
        賬號: <input type="text" name="userName"><br>
        密碼: <input type="text" name="passWord"
><br> <input type="submit" value="提交"> </form>
public class UserAction {

    public String execute() {

        HttpServletRequest request = ServletActionContext.getRequest();
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");

        return "success";
    }
}

第三種:可以在action裡面定義一個user物件,然後寫上對應的Setters和Getters方法獲取

    <form action="user/LoginAction.html" method="post"> 
        賬號: <input type="text" name="user.userName"><br>
        密碼: <input type="text" name="user.passWord"><br>
        <input type="submit" value="提交">
    </form>
public class UserAction {

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String execute() {

        System.out.println(user.getUserName()+">>"+user.getPassWord()); 

        return "success";
    }
}

第四種:通過實現ModelDriven介面獲取獲取(推薦)

    <form action="user/LoginAction.html" method="post"> 
        賬號: <input type="text" name="userName"><br>
        密碼: <input type="text" name="passWord"><br>
        <input type="submit" value="提交">
    </form>
public class QueryAllAction implements ModelDriven<User> {

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String execute() {
        System.out.println(user.getUserName());
        System.out.println(user.getPassWord());
        return "success";
    }

    @Override
    public User getModel() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

}

注:標籤form表單中的action屬性地址中的html字尾名是自己在配置檔案中加的字尾名。