Action: public String scope() throws Exception{ ActionContext ctx = ActionContext.getContext(); ctx.getApplication().put("app", "應用範圍");//往ServletContext裏放入app ctx.getSession().put("ses", "session範圍");//往session裏放入ses ctx.put("req", "request範圍");//往request裏放入req //System.out.println("servletContext.getAttribute : " + (String) (ctx.getApplication().get("app"))); return "scope"; }
JSP: ${applicationScope.app}<br> ${sessionScope.ses}<br> ${requestScope.req}<br>
public String rsa() throws Exception{ HttpServletRequest request = ServletActionContext.getRequest(); ServletContext servletContext = ServletActionContext.getServletContext(); HttpServletResponse response = ServletActionContext.getResponse(); HttpSession session = request.getSession(); return "scope"; }方法2,實現指定接口, 由struts框架運行時注入:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{ private HttpServletRequest request; private ServletContext servletContext; private HttpServletResponse response; public void setServletRequest(HttpServletRequest req) { this.request = req; } public void setServletResponse(HttpServletResponse res) { this.response = res; } public void setServletContext(ServletContext ser) { this.servletContext = ser; } }
(本學習筆記是根據傳智播客的視頻教程整理而來) html