三大框架(ssh)學習——表單資料封裝
Model-Driven和Property-Driven
Struts1中我們可以將提交表單的引數使用FormBean進行封裝傳遞給我們的Action。在struts2中我們可以使用Model-Driven和Property-Driven進行表單資料的封裝,便於我們在Action中直接使用。
Property-Driven使用示例:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>測試struts2</title> </head> <body> <form action=ceshi/User 使用者名稱:<input type=text name=uname /><br/> 密碼:<input type=password name=pwd /><br/> <input type=submit value=登陸/> </form> </body> </html> |
package com.bjsxt.struts.test;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport{
private String uname; private String pwd;
public String execute() throws Exception { System.out.println(getUname()); return this.SUCCESS; }
public String getUname() { return uname; }
public void setUname(String uname) { this.uname = uname; }
public String getPwd() { return pwd; }
public void setPwd(String pwd) { this.pwd = pwd; } } |
package com.bjsxt.struts.test;
public class User { private int id; private String uname; private String pwd; //get和set方法省略! }
|
屬性驅動時,只要保持表單域名字和Action屬性名一致,即可自動進行值得填充。
Model-Driven使用示例:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>測試struts2</title> </head> <body> <form action=ceshi/User> 使用者名稱:<input type=text name=uname /><br/> 密碼:<input type=password name=pwd /><br/> <input type=submit value=登陸/> </form> </body> </html> |
package com.bjsxt.struts.test;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
public String execute() throws Exception { System.out.println(user.getUname()); return this.SUCCESS; }
@Override public User getModel() { return user; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; } } |
package com.bjsxt.struts.test;
public class User { private int id; private String uname; private String pwd; //限於篇幅,get和set方法省略! }
|
測試:http://localhost/teststruts/login.jsp 提交表單,發現後臺正確獲取輸入的資料:
屬性驅動和模型驅動的選取:
- 屬性驅動方便簡潔。表單域較少時可用。
- 表單域較多且定義了相應的pojo,可以使用模型驅動。