Struts2:访问servlet三大域request/session/application属性

第一种:伪访问,通过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;

  }

}


你可能感兴趣的:(Struts2:访问servlet三大域request/session/application属性)