Struts2 访问或添加request/session/application属性
action代码
publicStringscope()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>
如果只是往对象中注入值,建议使用上一中方法;
获取HttpServletRequest/HttpSession/ServletContext/HttpServletResponse对象有两种方法:
方法一:通过ServletActionContext.类直接获取:publicStringrsa()throwsException{
HttpServletRequestrequest=ServletActionContext.getRequest();
ServletContextservletContext=ServletActionContext.getServletContext();
request.getSession()
HttpServletResponseresponse=ServletActionContext.getResponse();
return"scope";
}
方法二,实现指定接口,由struts框架运行时注入:publicclassHelloWorldActionimplementsServletRequestAware,ServletResponseAware,ServletContextAware{
privateHttpServletRequestrequest;
privateServletContextservletContext;
privateHttpServletResponseresponse;
publicvoidsetServletRequest(HttpServletRequestreq){
this.request=req;
}
publicvoidsetServletResponse(HttpServletResponseres){
this.response=res;
}
publicvoidsetServletContext(ServletContextser){
this.servletContext=ser;
}
}
注:建议使用第一种方法