Servlet之间通信的方式有两大类,每个类有三种不同的方法
1.request
2.session
3.application
不实现ServletContextAware,SessionAware,ServletRequestAware这三个接口的通信
HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("request_username", "username"); HttpServletResponse response = ServletActionContext.getResponse(); //这个是Servlet的session // HttpSession session = request.getSession(); // session.setAttribute("session_username", "username");
ServletContext servletContext = ServletActionContext.getServletContext(); servletContext.setAttribute("application_username", "username");
实现ServletContextAware,SessionAware,ServletRequestAware这三个接口的通信
public class Servlet2Action extends ActionSupport implements ServletContextAware,SessionAware,ServletRequestAware { private HttpServletRequest request; private ServletContext servletContext; private Map<String,Object> sessionMap; /** * {}struts2包装以后的session,本质上是一个map org.apache.catalina.core.ApplicationContextFacade@72898540 servlet中的application org.apache.struts2.dispatcher.StrutsRequestWrapper@228b677f struts2包装后的request */ public void setSession(Map<String, Object> arg0) { this.sessionMap=arg0; sessionMap. } public void setServletContext(ServletContext arg0) { this.servletContext=arg0; } public void setServletRequest(HttpServletRequest arg0) { this.request=arg0; } public String testServelet() { System.out.println(sessionMap.toString()); System.out.println(servletContext.toString()); System.out.println(request.toString()); return "servelet"; } }
在目标页面取出
request:${requestScope.request_username }<br> session:${sessionScope.session_username }<br> application:${applicationScope.application_username }<br>