一.注意点
- 建立实现ModelDriven接口的action类
- 在该action类中,创建实体对象并new
- 在getModel返回该对象
- 在显示页面中提交的表单name正常写
二.案例
创建实体类User:
package com.ahd.entity;import com.opensymphony.xwork2.ModelDriven;public class User{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;} }
创建实现ModelDriven接口的action类UserModelAction:
package com.ahd.action;import com.ahd.entity.User;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ModelDriven;public class UserModelAction implements ModelDriven{ User user=new User();@Overridepublic Object getModel() {// TODO Auto-generated method stubreturn user;}public String execute(){System.out.println(user.getUsername()+user.getPassword());return Action.SUCCESS;}}
提交表单页面编写(关键代码):
1 <form action="userModel.action"> 2 用户名:<input type="text" name="username"/><br/> 3 密 码:<input type="password" name="password"/><br/> 4 <input type="submit" value="submit"/> 5 <input type="reset" name="reset"/><br/> 6 </form>
struts.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""struts-2.0.dtd"><struts><package name="struts2" extends="struts-default" namespace=""><action name="userModel" class="com.ahd.action.UserModelAction"><result>/success.jsp</result></action></package> </struts>
web.xml文件(关键代码)
<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>