struts2 获取 request response几种方法

一、使用 Aware拦截器
这种方法需要Action类实现相应的拦截器接口。代码如下

...
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
...
public class AdminAction implements Action, RequestAware, ServletResponseAware{
    private Map request;
    private HttpServletResponse response;
    @Override
    public void setRequest(Map request) {
        this.request = request;
    }
    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
...
}

二、 使用ActionContext类,比较简单。代码如下

...
import com.opensymphony.xwork2.ActionContext;
...
public class MyAction implements Action {

    private ActionContext atx = ActionContext.getContext();
    private HttpServletRequest request = (HttpServletRequest) atx.get(ServletActionContext.HTTP_REQUEST);
    private HttpServletResponse response = (HttpServletResponse) atx.get(ServletActionContext.HTTP_RESPONSE);
...
}

三、使用servletactioncontext类,最简单的方式。代码如下

import org.apache.struts2.ServletActionContext;
...
public class MyAction implements Action {
    private HttpServletRequest request = ServletActionContext.getRequest();
    private HttpServletResponse response = ServletActionContext.getResponse();
...
}

最简单的就是最后一个,根据需求自己选择吧~~

你可能感兴趣的:(struts2 获取 request response几种方法)