Struts2 Action参数接收:属性、DomainModel与ModelDriven
"Struts2框架允许Action类以多种方式接收请求参数,主要涉及Action的属性、DomainModel以及ModelDriven接口。以下是对这三种方法的详细说明:" 1. 使用Action的属性接收参数 - 定义:在Action类内部,声明一个与请求参数名称相匹配的私有属性,例如`private String userName;`,然后提供对应的getter和setter方法,如`public String getUserName(){}` 和 `public void setUserName(String userName){}`。 - 接收:当Struts2处理请求时,会自动调用setter方法将请求参数值赋给Action的属性。例如,如果URL中有`?userName=Magic`,Struts2会调用`setUserName("Magic")`。 - 发送:在JSP或其他视图层组件中,可以通过`user1!add`这样的Action方法引用,并在URL中以`userName=Magic`的形式传递参数。 2. 使用DomainModel接收参数 - 定义:创建一个独立的Model类,比如`User`,包含相应的属性和getter/setter方法。在Action类中,声明一个`User`类型的属性,但不需要手动创建对象,例如`private User user;`。 - 接收:Struts2会自动创建Model对象并调用setter方法填充属性,Action可以通过`user.getUserName()`来访问请求参数。 - 发送:在请求URL中,参数以`user2!add?user.userName=MGC`的方式传递,这里的`user`是Model对象的属性名,`userName`是Model类中的属性。 3. 使用ModelDriven接口接收参数 - 定义:让Action类实现`ModelDriven`接口,这个接口要求实现`getModel()`方法,返回Model对象。通常在Action类中会有一个Model类的实例,如`private User user = new User();`。 - 接收:Struts2会调用`getModel()`方法获取Model对象,然后自动填充参数,Action同样通过`user.getUserName()`访问参数。 - 发送:请求URL中的参数传递方式与使用DomainModel相同,即`user2!add?userName=MGC`。 在配置文件`web.xml`中,Struts2过滤器是必要的,它定义了Struts2的拦截器链,使得Action能够正确地接收和处理请求。示例配置如下: ```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> ``` 这些配置确保了所有请求都会经过Struts2框架,使得Action可以利用上述方法接收参数。Struts2的这种灵活性使得开发人员可以根据项目需求选择最合适的方式来处理请求参数。
下载后可阅读完整内容,剩余4页未读,立即下载
- 粉丝: 0
- 资源: 3
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- ExtJS 2.0 入门教程与开发指南
- 基于TMS320F2812的能量回馈调速系统设计
- SIP协议详解:RFC3261与即时消息RFC3428
- DM642与CMOS图像传感器接口设计与实现
- Windows Embedded CE6.0安装与开发环境搭建指南
- Eclipse插件开发入门与实践指南
- IEEE 802.16-2004标准详解:固定无线宽带WiMax技术
- AIX平台上的数据库性能优化实战
- ESXi 4.1全面配置教程:从网络到安全与实用工具详解
- VMware ESXi Installable与vCenter Server 4.1 安装步骤详解
- TI MSP430超低功耗单片机选型与应用指南
- DOS环境下的DEBUG调试工具详细指南
- VMware vCenter Converter 4.2 安装与管理实战指南
- HP QTP与QC结合构建业务组件自动化测试框架
- JsEclipse安装配置全攻略
- Daubechies小波构造及MATLAB实现