struts2 中怎样获取HttpServletRequest 和HttpServletResponse
提供两种方法
第一种通过调用ServletActionContext这个类源代码中提供这个对象。
*/ public static void setRequest(HttpServletRequest request) { ActionContext.getContext().put(HTTP_REQUEST, request); } /** * Gets the HTTP servlet request object. * * @return the HTTP servlet request object. */ public static HttpServletRequest getRequest() { return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST); } /** * Sets the HTTP servlet response object. * * @param response the HTTP servlet response object. */ public static void setResponse(HttpServletResponse response) { ActionContext.getContext().put(HTTP_RESPONSE, response); } /** * Gets the HTTP servlet response object. * * @return the HTTP servlet response object. */ public static HttpServletResponse getResponse() { return (HttpServletResponse) ActionContext.getContext().get(HTTP_RESPONSE); } /** * Gets the servlet context. * * @return the servlet context. */ public static ServletContext getServletContext() { return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT); }
调用方法
ServletActionContext.getPageContext();
ServletActionContext.getRequest();
ServletActionContext.getResponse();
ServletActionContext.getContext();
第二种方法:通过实现ServletRequestAware接口 来实现
代码如
public class Demo2Action extends ActionSupport implements ServletRequestAware{ private HttpServletRequest request; public String execute(){ System.out.print(request); return NONE; } //调用动作方法前 框架先会调用此方法 将request对象注入进来 public void setServletRequest(HttpServletRequest request) { this.request=request; } }
这样也能够实现得到HttpServletRequest