struts2的action类中,字段的属性对应页面表单字段的属性,这个是怎么实现的呢?
是通过拦截器把Action的属性值设置进去的。在“defaultStack”interceptor-stack中有个“param”拦截器:com.opensymphony.xwork2.interceptor.ParametersInterceptor,在这个拦截器的方法:
[code="java"]
public String doIntercept(ActionInvocation invocation) throws Exception {
Object action = invocation.getAction();
if (!(action instanceof NoParameters)) {
ActionContext ac = invocation.getInvocationContext();
final Map 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();
}
[/code]
在setParameters方法里有具体设置属性的操作,你可以看到这么一段:
[code="java"]
...
try {
newStack.setValue(name, value);
} catch (RuntimeException e) {
...
}
...
[/code]
使用页面中的变量
<%
String name = "fireinjava";
request.setAttribute("name ", name );
%>
页面中的<input name="xx" 对应action中的
private String xx;
public void setXx(String xx){
this.xx=xx;
}
public String getXx(){
return this.xx;
}
你看源码,其中有部分就是把params封装到一个map里面
看源码是你最好的选择!