Struts2框架访问Servlet API
使用解耦的方式访问Servlet API
1.使用ActionContext类获取Servlet API对象对应的map对象
/ 获取HttpServletRequest对应的对应的map对象
Map request = (Map)ActionContext.getContext().get("request");
/ 获取HttpSession对应的对应的map对象
Map session = ActionContext.getContext().getSession();
/ 获取ServletContext对应的对应的map对象
Map application = ActionContext.getContext().getApplication();
2.实现特定接口,向Action注入Servlet API对象对应的Map对象
实现org.apache.struts2.interceptor.RequestAware接口
public void setRequest(Map<String, Object> request) {}
实现org.apache.struts2.interceptor.SessionAware接口
public void setSession(Map<String, Object> session) {}
实现org.apache.struts2.interceptor.ApplicationAware接口
public void setApplication(Map<String, Object> application) {}
使用耦合的方式访问Servlet API
1.使用ServletActionContext类获取Servlet API对象
/ 获取HttpServletRequest对象
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("参数名", 参数值);
request.getAttribute("参数名");
/ 获取HttpServletResponse对象
HttpServletResponse response = ServletActionContext.getResponse();
response.sendRedirect("重定向路径");
response.getWriter();
/ 获取HttpSession对象
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute("参数名", 参数值);
session.getAttribute("参数名");
/ 获取ServletContext对象
ServletContext servletContext = ServletActionContext.getServletContext();
servletContext.getContextPath();
2.向Action注入Servlet API对象
实现org.apache.struts2.interceptor.ServletRequestAware接口
void setServletRequest(HttpServletRequest request) {}
实现org.apache.struts2.interceptor.ServletResponseAware接口
void setServletResponse(HttpServletResponse response) {}
实现org.apache.struts2.interceptor.ServletContextAware接口
void setServletContext(ServletContext context) {}
如何选择访问Servlet API的方式?
1.优先使用ActionContext
2.除非需要访问如下对象,才使用ServletActionContext
request.getServletPath()
request.getPathInfo()
request.getContextPath()
request.getRequestURI()
……