在传统的sevlet中,想要获取表单中的元素,使用request.getParameter("xxx")来获取,作为框架的struts2,显然应该有更为方便的获取表单属性的方式。
下面来介绍一下获取表单元素的两种方式:
(1)action中属性的名称和页面上name的名称保持一致
(2)属性必须有set和get方法
1.jsp表单提交到action:testPropertyDriver.jsp
<%@ page language="java" import= "java.util.*" pageEncoding="UTF-8" %>
<%@
taglib uri="/struts-tags" prefix= "s"%>
<!
DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html
>
<
body
>
<
s:form
action="../propertyDriverAction_showData.action" >
用户名:
<s:textfield name="username" ></s:textfield>
密码:
<s:password name="password" ></s:password>
<s:submit></ s:submit>
</
s:form
>
</
body
>
</
html
>
|
2.Action获取表单数据,Action中需要有username和password这两个field,并提供get/set方法!
此时
public
class PropertyDriverAction extends ActionSupport{
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;
}
public
String showData(){
ActionContext. getContext().getValueStack().setValue(
"username"
,
"adsfasdf");
return "propertydriver" ;
}
}
|
3.struts.xml和result页面:propertydriver.jsp
配置文件:
<
struts
>
<
package
name="propertydriver" namespace="/" extends="struts-default" >
<action name= "propertyDriverAction_*" method="{1}" class="cn.itheima03.struts2.propertydriver.action.PropertyDriverAction" >
<result name="propertydriver" >propertydriver/propertydriver.jsp</result >
</action>
</
package
>
</
struts
>
|
propertydriver.jsp:
<%@
page language="java" import= "java.util.*" pageEncoding="UTF-8" %>
<%@
taglib uri="/struts-tags" prefix= "s"%>
<!
DOCTYPE
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<
html
>
<body >
<s:property value= "username"/><br />
<s:property value= "password"/>
</body >
</
html
>
|
二、模型驱动
当表单属性过多时,如果依旧采用如上方法,需要大量的篇幅来写get/set方法,这时候可以将表单参数自动封装成为一个bean!
下面是原理图:
Action代码为:
public
class ModelDriverAction extends ActionSupport implements ModelDriven<User>{
private
User user = new User();
public
String testModelDriver(){
return "modeldriver" ;
}
//必须要有这个方法
public
User getModel() {
return this.user;
}
}
|
另外两个jsp文件与上一致!