Struts2 在Action中獲取request、session、servletContext的三種方法


首頁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;
}
}




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com