1. 访问和添加request/session/application属性
如果只是往request/session/application中设置属性,可以用下面的方式
Java代码
ActionContextctx=ActionContext.getContext();
ctx.getApplication().put("app","应用范围");//往ServletContext里放入app
ctx.getSession().put("ses","session范围");//往session里放入ses
ctx.put("req","request范围");//往request里放入req
ctx.put("names",Arrays.asList("老张","老黎","老方"));
ActionContext ctx = ActionContext.getContext(); ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app ctx.getSession().put("ses", "session范围");//往session里放入ses ctx.put("req", "request范围");//往request里放入req ctx.put("names", Arrays.asList("老张", "老黎", "老方"));
jsp页面上获取方式
Java代码
${applicationScope.app}<br>
${sessionScope.ses}<br>
${requestScope.req}<br>
${applicationScope.app}<br> ${sessionScope.ses}<br> ${requestScope.req}<br>
2. struts2中如何获取httpServletRequest/HttpSession/ServletContext/HttpServletResponse对象
方法一,通过ServletActionContext类获取:(推介使用)
Java代码
publicStringrsa()throwsException{
HttpServletRequestrequest=ServletActionContext.getRequest();
ServletContextservletContext=ServletActionContext.getServletContext();
request.setAttribute("req","请求范围属性");
request.getSession().setAttribute("ses","会话范围属性");
servletContext.setAttribute("app","应用范围属性");
HttpServletResponseresponse=ServletActionContext.getResponse();
return"message";
}
public String rsa() throws Exception{ HttpServletRequest request = ServletActionContext.getRequest(); ServletContext servletContext = ServletActionContext.getServletContext(); request.setAttribute("req", "请求范围属性"); request.getSession().setAttribute("ses", "会话范围属性"); servletContext.setAttribute("app", "应用范围属性"); HttpServletResponse response = ServletActionContext.getResponse(); return "message"; }
方法二,实现指定接口,由struts框架注入:
Java代码
importcom.opensymphony.xwork2.ActionContext;
publicclassHelloWorldAction2implementsServletContextAware,ServletRequestAware,ServletResponseAware{
privateHttpServletRequestrequest;
privateHttpServletResponseresponse;
privateServletContextservletContext;
publicvoidsetServletContext(ServletContextcontext){
//context对象不是应用程序传进去的,而是由struts框架自动注入的
this.servletContext=context;
}
publicvoidsetServletRequest(HttpServletRequestrequest){
this.request=request;
}
publicvoidsetServletResponse(HttpServletResponseresponse){
this.response=response;
}