Struts2中表单与Action传递数据三种方式

转自:http://gty.vip.blog.163.com/blog/static/1192114782009759355784/

1.       Action中的属性与表单中的属性一致就可以

JSP中的表单

<formaction="login.action"method="post">

    用户名:<inputtype="text"name="username"/>    <br/>

    密码:  <inputtype="password"name="password"/><br/>

    <inputtype="submit"value="登陆"/>

</form>



Action中的属性                                                       

publicclassLoginActionextends ActionSupport {

    private String username;

    private String password;

  

    public String getUsername() {

       returnusername;

    }

    publicvoid setUsername(String username) {

       this.username = username;

    }

    public String getPassword() {

       returnpassword;

    }

    publicvoid setPassword(String password) {

       this.password = password;

    }

  

    public String execute(){

       if( username.equalsIgnoreCase("aaa")&&password.equals("aaaaaa")){

           returnSUCCESS;

       }

       else{

           returnERROR;

       }

    }

}

2.       使用一个VO类

在表单中提交的属性名改为user.username

<formaction="login.action"method="post">

       用户名:<inputtype="text"name="user.username"/>  <br/>

       密码:  <inputtype="password"name="user.password"/><br/>

       <inputtype="submit"value="登陆"/>

    </form>

LoginAction中的属性改为user

publicclassLoginActionextends ActionSupport{

    private User user;

  

    public User getUser() {

       returnuser;

    }

    publicvoid setUser(User user) {

       this.user = user;

    }



    public String execute(){

       if( user.getUsername().equalsIgnoreCase("aaa")&&user.getPassword().equals("aaaaaa")){

           returnSUCCESS;

       }

       else{

           returnERROR;

       }

    }

}





3.       使用Struts2中的ModelDriven数据模式

Action类要实现一个泛型接口,前台表单与1相同

publicclassLoginActionextends ActionSupport implements ModelDriven<User> {

    private User user = new User();

  

    public String execute(){

       if( user.getUsername().equalsIgnoreCase("aaa")&&user.getPassword().equals("aaaaaa")){

           returnSUCCESS;

       }

       else{

           returnERROR;

       }

    }



    public User getModel() {

       returnuser;

    }

}

你可能感兴趣的:(jsp,Blog)