1. 编写一个简单的Action
public class UserAction {
private String name;
public String execute(){
System.out.println("执行execute方法...");//加断点
System.out.println("name========"+name);
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2. 启动Tomcat服务器调试运行
3. 查看代码执行顺序
4. 打开Dispather的serviceAction方法
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
throws ServletException {
//在下面一行代码加断点再次调试运行
Map<String, Object> extraContext = createContextMap(request, response, mapping);
.....
在该行按F5键进入如下代码
public Map<String,Object> createContextMap(request, response,mapping) {
Map requestMap = new RequestMap(request);
从以下注释可以看出参数request获取参数的方式,存在Map中
// parameters map wrapping the http parameters. ActionMapping parameters are now handled and applied separately
HttpParameters params = HttpParameters.create(request.getParameterMap()).build();
在build方法按F3可以看到如下代码
public HttpParameters build() {
...
for (Map.Entry<String, Object> entry : requestParameterMap.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
parameters.put(name, new Parameter.Request(name, value));
}
return new HttpParameters(parameters);
}
可以看出把请求参数的Map包装成HttpParameters
最后创建一个map
Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response);
....
return extraContext;
5. 查看具体参数位置
public void serviceAction(request, response, mapping)
throws ServletException {
//加断点调试
Map<String, Object> extraContext = createContextMap(request, response, mapping);
// If there was a previous value stack, ....
ValueStack stack = .....;
查看extraContext 变量中的数据如下图所示,可以看到调用Action时传入的参数:http://localhost:8080/strutsdemo/userAction?name=admin
这就是Struts2获取请求参数的过程。