🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 原理 ![](https://box.kancloud.cn/fd7cf72c34136698a84a6f5c70ef149e_1468x662.png) Struts2框架在运行时,请求会被StrutsPrepareAndExecuteFilter拦截,会根据请求,去 strtus.xml文件中查找到匹配的action,在action执行前,会走一些interceptor 默认执行的拦截器是struts-default.xml文件中定义的。 在默认执行的拦截器中有一个 ![](https://box.kancloud.cn/0dd38403df9c8d514fedb1fe59350106_1746x150.png) 查看一下ServletConfigInterceptor源代码 以下是部分源代码 ![](https://box.kancloud.cn/c9b15fb29b979517e52e5cac272d0317_1714x542.png) ServletRequestAware, 实现这个接口可以获取HttpServletRequest ServletResponseAware ,实现这个接口可以获取HttpServletResponse ServletContextAware 实现这个接口可以获取ServletContext # 通过ActionContext 推荐 ~~~ // request域 => map (struts2并不推荐使用原生request域) // 不推荐 //import java.util.Map; Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request"); // 推荐 ActionContext.getContext().put("name", "requestTom"); // session域 => map Map<String, Object> sessionScope = ActionContext.getContext().getSession(); sessionScope.put("name", "sessionTom"); // application域=>map Map<String, Object> applicationScope = ActionContext.getContext().getApplication(); applicationScope.put("name", "applicationTom"); System.out.println(ActionContext.getContext().get("name")); System.out.println(sessionScope.get("name")); System.out.println(applicationScope.get("name")); ~~~ # 通过ServletContext 不推荐 ~~~ // import javax.servlet.ServletContext; // import javax.servlet.http.HttpServletRequest; // import javax.servlet.http.HttpServletResponse; // import javax.servlet.http.HttpSession; // 不推荐 // 原生request HttpServletRequest request = ServletActionContext.getRequest(); // 原生session HttpSession session = request.getSession(); // 原生response HttpServletResponse response = ServletActionContext.getResponse(); // 原生ServletContext ServletContext servletContext = ServletActionContext.getServletContext(); ~~~ # 通过实现接口方式 想要什么就实现什么接口,ServletXXXXXAware ~~~ package domain; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; public class HelloAction implements ServletRequestAware { private HttpServletRequest request; public String hello() { System.out.println("原生request: " + request); return "success"; } @Override public void setServletRequest(HttpServletRequest arg0) { // TODO Auto-generated method stub this.request = arg0; } } ~~~