Struts2 HttpServletRequest获取请求参数的过程

本文介绍了如何在Struts2框架中实现一个简单的Action,并详细解释了请求参数是如何被解析和传递给Action类的方法。通过逐步调试的方式展示了从HTTP请求到Action执行过程中的参数流转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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获取请求参数的过程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值