struts2绑定页面参数三种方式
1.普通属性:在action中写与页面参数相同的属性名,然后set方法
2.用对象来接收:在action中写一个对象,表单元素名改为:对象名.属性名
3.用实现ModelDriven<T>接口:在action中写一个对象并且要初始化,重写getModel方法,页面表单元素不需要修改
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="login" method="post"> 用户名:<input name="username"><br> 或 <input name="user.username"><br>
密码:<input type="password" name="pwd"><br> <input type="submit" value="提交"> </form> </body> </html>
LoginAction.java
package com.action; import com.opensymphony.xwork2.ModelDriven; import com.pojo.User; public class LoginAction implements ModelDriven<User>{ //1.用属性绑定参数 // String username; // String pwd; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPwd() { // return pwd; // } // // public void setPwd(String pwd) { // this.pwd = pwd; // } //2.用pojo对象绑定页面参数 // User user; // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } //3.用pojo对象绑定,用ModelDriver接口来实现 User user = new User(); @Override public User getModel() { // TODO Auto-generated method stub return user; } public String execute(){ System.out.println("我的struts2第一个action"); System.out.println("username="+user.getUsername()+"pwd="+user.getPwd()); return "success"; } }