标签:
在struts2中有两种方式可以得到这些对象
1、非IoC方式
要获得上述对象,关键Struts 2中com.opensymphony.xwork2.ActionContext类。我们可以通过它的静态方法getContext()获取当前Action的上下文对象。有了这个对象我们想获得其他几个对象就好办了
ActionContext ctx = ActionContext.getContext();
Map session = ctx.getSession();
细心的朋友可以发现这里的session是个map对象在Struts2中底层的session都被封装成了Map类型我们可以直接操作这个map 进行对session的写入和读取操作而不用去直接操作HttpSession对象
另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象。
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象。
2、IoC方式(这种方式在tapestry中也是这样实现的)
要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。具体实现
publicclass IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
private String message;
private Map att;
private HttpServletRequest request;
private HttpServletResponse response;
public String getMessage() {
return message;
}
publicvoid setSession(Map att) {
this.att = att;
}
publicvoid setServletRequest(HttpServletRequest request) {
this.request = request;
}
publicvoid setServletResponse(HttpServletResponse response) {
this.response = response;
}
@Override
public String execute() {
att.put("msg", "Hello World from Session!");
HttpSession session = request.getSession();
StringBuffer sb =new StringBuffer("Message from request: ");
sb.append(request.getParameter("msg"));
sb.append("
Response Buffer Size: ");
sb.append(response.getBufferSize());
sb.append("
Session ID: ");
sb.append(session.getId());
message = sb.toString();
return SUCCESS;
}
}
在struts.xml的action中配置拦截器
<interceptor-ref name="servletConfig"></interceptor-ref>
struts2的action中获得request response session 对象
标签:
原文地址:http://www.cnblogs.com/toSeeMyDream/p/5539313.html