Struts2 在Action中获取request、session、servletContext的三种方法

时间:2023-04-19 23:49:50

首页message.jsp:

<body>
${requestScope.req }<br/>
${applicationScope.app }<br/>
${sessionScope.ses }<br/>
</body>

(1)使用ActionContext获取

public String sayHello(){
ActionContext cxt=ActionContext.getContext();
cxt.getApplication().put("app", "application范围");
cxt.getSession().put("ses", "session范围");
cxt.put("req", "request范围");
return "message";
}

(2)使用ServletActionContext获取

public String sayTwo(){
HttpServletRequest request=ServletActionContext.getRequest();
ServletContext cxt=ServletActionContext.getServletContext();
request.setAttribute("req", "request请求范围");
request.getSession().setAttribute("ses", "会话范围");
cxt.setAttribute("app", "应用程序范围");
return "message";
}

(3)通过继承ServletRequestAware,ServletContextAware 并实现set方法获取

public class HelloAction implements ServletRequestAware,ServletContextAware{
private HttpServletRequest request1;
private ServletContext context1; public HelloAction(){} public String sayThree(){
request1.setAttribute("req", "request请求范围111");
request1.getSession().setAttribute("ses", "会话范围111");
context1.setAttribute("app", "应用程序范围111");
return "message";
}
@Override
public void setServletRequest(HttpServletRequest arg0) {
request1=arg0;
}
@Override
public void setServletContext(ServletContext arg0) {
context1=arg0;
}
}