第一种:伪访问,通过ActionContext,将属性放入Map中,Struts2的拦截器会自动转换。
public String scope() throwsException{
ActionContextctx =ActionContext.getContext();
ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app
ctx.getSession().put("ses", "session范围");//往session里放入ses
ctx.put("req","request范围");//往request里放入req
return "scope";
}
JSP:
<body>
${applicationScope.app} <br>
${sessionScope.ses}<br>
${requestScope.req}<br>
</body>
第二种: 通过 ServletActionContext . 类直接获取:public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContextservletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return"scope";
}
第三种: 实现指定接口,由 struts 框架运行时注入:public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
privateHttpServletRequest request;
privateServletContextservletContext;
privateHttpServletResponse response;
publicvoid setServletRequest(HttpServletRequestreq) {
this.request=req;
}
publicvoid setServletResponse(HttpServletResponse res) {
this.response=res;
}
publicvoid setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}