理解Struts2的Action中的setter方法是怎么工作的
接触过webwork和Struts2的同行都应该知道,
提交表单的时候,只要Action中的属性有setter 方法,这些表单数据就可以正确赋值到Action中属性里;
另外对于Spring配置文件中声明的bean,也可以在Action中声明setter 方法将其注入到Action实例中。
那么现在要研究:这些是怎么工作的呢?
(1)提交表单时的参数
在struts2-core-2.3.1.2.jar压缩包内的struts-default.xml配置文件中有这个配置:
<interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>
这个拦截器是负责解析请求中的URL参数,并赋值给action中对应的属性
来看代码:
- //com.opensymphony.xwork2.interceptor.ParametersInterceptor.java
- //主要代码如下:
- //...
- @Override
- public String doIntercept(ActionInvocation invocation) throws Exception {
- Object action = invocation.getAction();
- if (!(action instanceof NoParameters)) {
- ActionContext ac = invocation.getInvocationContext();
- final Map<String, Object> parameters = retrieveParameters(ac);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Setting params " + getParameterLogMap(parameters));
- }
- if (parameters != null) {
- Map<String, Object> contextMap = ac.getContextMap();
- try {
- ReflectionContextState.setCreatingNullObjects(contextMap, true);
- ReflectionContextState.setDenyMethodExecution(contextMap, true);
- ReflectionContextState.setReportingConversionErrors(contextMap, true);
- ValueStack stack = ac.getValueStack();
- setParameters(action, stack, parameters);
- } finally {
- ReflectionContextState.setCreatingNullObjects(contextMap, false);
- ReflectionContextState.setDenyMethodExecution(contextMap, false);
- ReflectionContextState.setReportingConversionErrors(contextMap, false);
- }
- }
- }
- return invocation.invoke();
- }
- protected void setParameters(Object action, ValueStack stack, final Map<String, Object> parameters) {
- ParameterNameAware parameterNameAware = (action instanceof ParameterNameAware)
- ? (ParameterNameAware) action : null;
- Map<String, Object> params;
- Map<String, Object> acceptableParameters;
- if (ordered) {
- params = new TreeMap<String, Object>(getOrderedComparator());
- acceptableParameters = new TreeMap<String, Object>(getOrderedComparator());
- params.putAll(parameters);
- } else {
- params = new TreeMap<String, Object>(parameters);
- acceptableParameters = new TreeMap<String, Object>();
- }
- for (Map.Entry<String, Object> entry : params.entrySet()) {
- String name = entry.getKey();
- boolean acceptableName = acceptableName(name)
- && (parameterNameAware == null
- || parameterNameAware.acceptableParameterName(name));
- if (acceptableName) {
- acceptableParameters.put(name, entry.getValue());
- }
- }
- ValueStack newStack = valueStackFactory.createValueStack(stack);
- boolean clearableStack = newStack instanceof ClearableValueStack;
- if (clearableStack) {
- //if the stack's context can be cleared, do that to prevent OGNL
- //from having access to objects in the stack, see XW-641
- ((ClearableValueStack)newStack).clearContextValues();
- Map<String, Object> context = newStack.getContext();
- ReflectionContextState.setCreatingNullObjects(context, true);
- ReflectionContextState.setDenyMethodExecution(context, true);
- ReflectionContextState.setReportingConversionErrors(context, true);
- //keep locale from original context
- context.put(ActionContext.LOCALE, stack.getContext().get(ActionContext.LOCALE));
- }
- boolean memberAccessStack = newStack instanceof MemberAccessValueStack;
- if (memberAccessStack) {
- //block or allow access to properties
- //see WW-2761 for more details
- MemberAccessValueStack accessValueStack = (MemberAccessValueStack) newStack;
- accessValueStack.setAcceptProperties(acceptParams);
- accessValueStack.setExcludeProperties(excludeParams);
- }
- for (Map.Entry<String, Object> entry : acceptableParameters.entrySet()) {
- String name = entry.getKey();
- Object value = entry.getValue();
- try {
- newStack.setParameter(name, value);
- } catch (RuntimeException e) {
- if (devMode) {
- String developerNotification = LocalizedTextUtil.findText(ParametersInterceptor.class, "devmode.notification", ActionContext.getContext().getLocale(), "Developer Notification:\n{0}", new Object[]{
- "Unexpected Exception caught setting '" + name + "' on '" + action.getClass() + ": " + e.getMessage()
- });
- LOG.error(developerNotification);
- if (action instanceof ValidationAware) {
- ((ValidationAware) action).addActionMessage(developerNotification);
- }
- }
- }
- }
- if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null))
- stack.getContext().put(ActionContext.CONVERSION_ERRORS, newStack.getContext().get(ActionContext.CONVERSION_ERRORS));
- addParametersToContext(ActionContext.getContext(), acceptableParameters);
- }
- //...
上面的代码ValueStack stack = ac.getValueStack();
表明,它是从当前Action上下文获取值栈(其实就类似一个全局Map集合,用来存储参数值或struts上下文全局变量),
然后由判断如果是当前action可以接受的参数(Action中有setter方法)就过滤出来,
调用这句“newStack.setParameter(name, value); ”来保存到值栈中,
保存到了值栈中其实action实例的属性就能拿到值了。
最后一句“addParametersToContext(ActionContext.getContext(), acceptableParameters); ”
表明它还把这些过滤出来的参数保存到了ActionContext上下文中,
这样,如果跳转的类型是forward(服务器内部重定向),
目标url中就会带上上次请求的url的所有有用的参数。
(2) Spring配置bean注入到Action中
来看一个简单的Action类:
- package com.liany.demo.pubs.org.employee.action;
- import java.util.List;
- import com.opensymphony.xwork2.ActionSupport;
- import com.liany.demo.pubs.org.employee.model.Employee;
- import com.liany.demo.pubs.org.employee.service.EmployeeService;
- public class EmployeeAction extends ActionSupport{
- private EmployeeService employeeService;
- private List list;
- private Employee employee = new Employee();
- public StringReader getStringReader() {
- StringReader is = null;
- try {
- is = new StringReader(xmlBuf.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
- return is;
- }
- public Employee getEmployee() {
- return employee;
- }
- public void setEmployee(Employee employee) {
- this.employee = employee;
- }
- public List getList() {
- return list;
- }
- public void setEmployeeService(EmployeeService employeeService) {
- this.employeeService = employeeService;
- }
- public String execute(){
- //列表
- list = this.employeeService.getEmployees();
- return "list";
- }
- public String view(){
- employee = this.employeeService.getEmployeeById(employee.getId());
- return "view";
- }
- public String edit(){
- if(employee.getId()!=null){
- //修改
- employee = this.employeeService.getEmployeeById(employee.getId());
- }else{
- //新增
- employee.setId(null);
- }
- return "input";
- }
- public String save(){
- this.employeeService.saveEmployee(employee);
- return "repage";
- }
- public String delete(){
- this.employeeService.deleteEmployeeById(employee.getId());
- return "repage";
- }
- }
上面Action中的employeeService对象其实是在Spring配置文件中声明的bean,
代码中给它定义一个public的setEmployeeService()方法,这样就可以将bean实例注入到
Action中的实例中,这个功能是在Struts过虑器初始化的时候初始化了一个全局变量,
从而使得调用action时,从spring ioc容器中找到这个bean,再set给action对象。
配置文件是在struts.properties 文件中声明:
struts.objectFactory = spring
struts.objectFactory.spring.autoWire = name
理解Struts2的Action中的setter方法是怎么工作的的更多相关文章
- struts2:数据校验,通过Action中的validate()方法实现校验,图解
根据输入校验的处理场所的不同,可以将输入校验分为客户端校验和服务器端校验两种.服务器端验证目前有两种方式: 第一种 Struts2中提供了一个com.opensymphony.xwork2.Valid ...
- struts2:数据校验,通过Action中的validate()方法实现校验(续:多业务方法时的不同验证处理)
前文:struts2:数据校验,通过Action中的validate()方法实现校验,图解 如果定义的Action中存在多个逻辑处理方法,且不同的处理逻辑可能需要不同的校验规则,在这种情况下,就需要通 ...
- struts2的占位符*在action中的配置方法
转自:https://blog.csdn.net/u012546338/article/details/68946633 在配置<action> 时,可以在 name,class,meth ...
- JavaWeb_(Struts2框架)Action中struts-default下result的各种转发类型
此系列博文基于同一个项目已上传至github 传送门 JavaWeb_(Struts2框架)Struts创建Action的三种方式 传送门 JavaWeb_(Struts2框架)struts.xml核 ...
- struts2开发action 的三种方法以及通配符、路径匹配原则、常量
struts2开发action 的三种方法 1.继承ActionSupport public class UserAction extends ActionSupport { // Action中业务 ...
- 在struts2的action中操作域对象(request、session)
在struts2的Action中,操作域对象一共有三种方式: 1.ActionContext(与servelt API无关联): //相当于request ActionContext.getConte ...
- Struts2中使用execAndWait后,在 Action中调用getXXX()方法报告java.lang.NullPointerException异常的原因和解决方法
使用 Struts2 编写页面,遇到一个要长时间运行的接口,因此增加了一个execAndWait ,结果在 Action 中调用 getContext()的时候报告异常 ActionContext c ...
- struts2对action中的方法进行输入校验---xml配置方式(3)
上面两篇文章已经介绍了通过编码java代码的方式实现action方法校验,这里我们介绍第二种方式:xml配置文件 首先我们来看一个样例: ValidateAction.java: package co ...
- struts2对action中的方法进行输入校验(2)
struts2输入校验流程: 1.类型转换器对请求參数运行类型转换,并把转换后的值赋给aciton中的属性 2.假设在运行类型转换的过程中出现异常,系统会将异常信息保存到ActionContext, ...
随机推荐
- 疯狂JAVA——第八章 java集合
集合类主要负责保存.盛装其他数据,因此集合类也被称为容器类. 数组元素既可以是基本类型的值,也可以是对象(实际上是保存的对象的引用): 集合里只能保存对象.
- makefile 中的赋值
1. 在makefile 中可以使用后面定义的变量,未定义的变量值为空 = 使用变量时执行赋值操作 := 立即执行赋值操作 ?= 如果没有赋值过,就赋予后面的值 += 将后面的值追加到原来的值后面 参 ...
- docker问题
Docker报错 WARNING: IPv4 forwarding is disabled. Networking will not work. 解决办法: # vim /usr/lib/sysctl ...
- IE8兼容background-size
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/web/images/bg.png',sizingMethod='sca ...
- hdoj1257(DP-LIS/贪心)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1257 方法1--贪心: 定义一个数组f[30005],由于题目没给数据量大小,故为了保险,开到最大(高 ...
- tf.cast()
一.函数 tf.cast() cast( x, dtype, name=None ) 将x的数据格式转化成dtype.例如,原来x的数据格式是bool, 那么将其转化成float以后,就能够将其转化成 ...
- Control(拆点+最大流)
Control http://acm.hdu.edu.cn/showproblem.php?pid=4289 Time Limit: 2000/1000 MS (Java/Others) Mem ...
- ftp指令集
想进行ftp相关编程,得了解ftp的指令集. 可参考:http://blog.csdn.net/weiyuefei/article/details/51758288 ftp的命令和指令集不同: 命令是 ...
- PAT L3-004 肿瘤诊断(三维广搜)
在诊断肿瘤疾病时,计算肿瘤体积是很重要的一环.给定病灶扫描切片中标注出的疑似肿瘤区域,请你计算肿瘤的体积. 输入格式: 输入第一行给出4个正整数:M.N.L.T,其中M和N是每张切片的尺寸(即每张切片 ...
- swift 设置图片动画组 iOS11之前 默认图片 设置不成功
在iOS 11 上, 1.先执行动画组 在设置图片执行帧动画,2.先设置图片在设置帧动画,执行帧动画 没有任何问题 在iOS 10和iOS9上,必须 执行 方法二(先设置图片在设置帧动画,执行帧动画 ...