Struts2之处理请求参数
时间:2017-1-11 11:05
1、Struts2是一个MVC框架,那么分别表示什么?
View:JSP
Model:Action
Controller:Action、StrutsPrepareAndExecuteFilter
2、为什么Action既是Model又是Controller?
因为Action本身可以作为一个JavaBean。
3、在Struts2中获取请求参数有两大种(三小种)方式可以获取:
1)属性驱动(在Action中添加属性,对Action的属性进行操作)
* 直接将Action作为一个Model,就可以得到请求参数,也就是将Action作为一个JavaBean,提供get/set方法。
这种方式底层是通过反射来实现的。
> 问题1:使用Action封装请求参数,会不会存在线程安全问题?
不会,每一次请求都会生成一个Action对象。
> 问题2:使用该方式封装数据,将数据封装到Action属性中,不可能将Action对象传递给业务层。
需要单独定义JavaBean,将Action属性封装到JavaBean
示例代码:
实现原理:
1、首先为Action类提供JavaBean属性,并提供get / set方法
2、在过滤器中添加如下代码,将请求参数封装到JavaBean中:
3、在Action中使用属性
------------------------------------------------------------------------------------------------------------------
* 创建独立的Model对象,页面通过ognl表达式封装
> 在Action中声明一个JavaBean对象
> private User user;
> 提供get/set方法:public User getUser()....
> 在页面中使用ognl表达式:<input type="text" name="user.username" />
优点:简单,解决了第一种封装的问题。
缺点:在页面中使用了ognl表达式,与Struts2框架耦合度高。
示例代码:
/*
------------------------------------------------------------------------------------------------------------------
这种方式底层通过Struts2中的一个interceptor进行了封装:
<interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />
@Override
// 相当于request.getParameters();
// 将参数赋值给Action中的JavaBean
------------------------------------------------------------------------------------------------------------------
2)模型驱动(在开发中应用比较多)
使用ModelDriven接口,对请求数据进行封装。
步骤:
* 声明一个JavaBean对象并且必须实例化对象。
> private User user = new User();
* Action类实现ModelDriven接口
> public class Login3Action extends ActionSupport implements ModelDriven
> public Object getModel() { return this.user; }
优点:解决了属性驱动存在的问题
* 不需要将Action封装成JavaBean
* 解决了在页面中使用ognl表达式的问题
缺点:一次只能封装一个JavaBean对象,getModel()方法只能返回一个Bean。
很多关于模型驱动的拦截器都是ModelDriven拦截器操作的:
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor
示例代码:
/*
实现原理:
1、在Action中声明一个初始化的JavaBean对象。
2、实现ModelDriven接口
3、重写getModel()方法
4、在拦截器中实现如下代码:
——将请求参数封装到集合(了解)
原理:使用ognl表达式实现。
1、将数据封装到List集合
页面:
用户名1:<input type="text" name="users[0].username" /><br/>
Action类:
private List<User> users;
get / set方法
2、将数据封装到Map集合
页面:
用户名1:<input type="text" name="users['aaa'].username" /><br/>
Action类:
private Map<String, User> users;
get / set方法
——总结
1、Action接收请求参数
* 关于Struts2中的MVC
* 属性驱动
> 直接将Action作为JavaBean。
> Action中封装JavaBean,在页面上需要使用ognl表达式来给组件起名。
* 模型驱动
> 让Action实现ModelDriven接口,重写getModel()方法实例化一个JavaBean对象,该方法返回的就是实例化的JavaBean对象。
* 关于请求参数封装到集合
> List
> Map
最新文章
- 5、ASP.NET MVC入门到精通——NHibernate代码映射
- 配置javac环境
- cnblogs开篇留念
- C语言字符串处理函数
- .net 应用迁移到Mono 工具 (Moma)
- 【leetcode】3Sum
- 详细Java中的内存泄漏
- mq_unlink
- 基于jQuery的图片相册滑出放大插件
- (中等) UESTC 360 Another LCIS ,线段树+区间更新。
- UGUI batch 规则和性能优化
- 浅谈Vue不同场景下组件间的数据交流
- cocoapods使用 swift注意事项
- TypeError: Error #1034: 强制转换类型失败:无法将 ";"; 转换为 Array。
- 2018-2019-2 《网络对抗技术》Exp0 Kali安装 Week1 20165225
- CentOS随笔——关机命令
- Setup Mission End
- zabbix3.0.4使用percona-monitoring-plugins插件来监控mysql5.6的详细实现过程
- 用conda管理Python包
- mac终端下连接阿里云服务器