设为首页 加入收藏

TOP

Stucts2 页面上的值如何与Action的属性值对应
2015-11-10 13:44:59 来源: 作者: 【 】 浏览:6
Tags:Stucts2 面上 如何 Action 属性 对应

在Strut2中,页面的数据和Action有两种基本对应方式:分别是:属性驱动(FieldDriven)和模型驱动(ModelDriven)。属性驱动又分为两种情况:一种是基本数据类型的属性对应:另一种是JavaBean风格的属性对应。下面就分别来看看它们是什么意思都如何实现。


属性驱动(FieldDriven):基本数据类型的属性对应


在index.jsp中,我是这样写的



? ? 账号:

? ? 密码:
? ?
?


在Action中是这样写的


public class HelloWorldAction extends ActionSupport{
?
? ? private String account;
? ? private String password;
? ?
? ? public String getAccount() {
? ? ? ? return account;
? ? }
? ? public void setAccount(String account) {
? ? ? ? this.account = account;
? ? }
? ? public String getPassword() {
? ? ? ? return password;
? ? }
? ? public void setPassword(String password) {
? ? ? ? this.password = password;
? ? }
? ?
? ? //其他代码省略....
}
可以发现,在页面上index.jsp的name的属性,和Action的属性是同一个名称的。这样一来,当页面提交的时候,Struts2会自动从request对象里把数据提取出来,然后按照名称进行对应,自动设置到Action属性里面去。


2.属性驱动FieldDriven(JavaBean风格的属性对应)


?(1)先看看域对象的写法,按照JavaBean的风格来写,示例代码如下:


public class HelloWorldModel {
? ?
? ? private String account;
? ? private String password;
? ? public String getAccount() {
? ? ? ? return account;
? ? }
? ? public void setAccount(String account) {
? ? ? ? this.account = account;
? ? }
? ? public String getPassword() {
? ? ? ? return password;
? ? }
? ? public void setPassword(String password) {
? ? ? ? this.password = password;
? ? }
}
(2)这时候Action写法也有变化,主要就是直接使用这个对象,其实就是定义一个属性就是这样对象类型,然后为这个属性提供相应的getter()和setter()方法即可。如果把这个属性的可访问属性设置为public就不需要getter()和setter()方法。Action修改后的示例代码如下:


?public class HelloWorldAction extends ActionSupport{
?
? ? private HelloWorldModel hwm =? new HelloWorldModel();
?
? ? public HelloWorldModel getHwm() {
? ? ? ? return hwm;
? ? }
?
? ? public void setHwm(HelloWorldModel hwm) {
? ? ? ? this.hwm = hwm;
? ? }
? ? //其他代码省略....
}


?(3)Action发生变化后,index.jsp页面中的内容也要进行相应的改变,否则数据就无法正确对应,主要是在相应的name属性上,添加一个域对象的前缀,指明这个值到底是对应到哪宇哥域对象里面去,示例如下:



? ? ? ? 账号:

? ? ? ? 密码:
? ? ? ?
? ?


3.模型驱动(ModelDriven)


? 它的基本实现方式让Action实现一个ModelDriven的接口,这个接口需要我们实现getModel的方法。这个方法的返回值就是Action所使用的数据模型对象。修改后的示例代码如下:


?public class HelloWorldAction extends ActionSupport implements ModelDriven{
?
? ? private HelloWorldModel hwm =? new HelloWorldModel();
?
? ? public Object getModel() {
? ? ? ? // TODO Auto-generated method stub
? ? ? ? return hwm;
? ? }
? ? //其他代码省略....
}


在index.jsp中也需要做相应的调整,主要是是去掉刚才给name属性添加的hwm前缀。其示例代码如下:


?


? ? ? ? 账号:

? ? ? ? 密码:
? ? ? ?
?


为什么种方式不需要前缀了呢?


? 因为使用这种ModelDriven的方式,一个Actiion只能对应一个Model,因此不需要添加前缀,Struts2j就知道,页面上account的值就对应到这个Model的account属性。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Struts2中的combobox标签使用 下一篇Python中定义字符串和修改字符串..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: