欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

struts2的action中获得request response session

程序员文章站 2022-07-03 23:23:18
...
在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>



文章转载自网管之家:[url]http://www.bitscn.com/pdb/java/200805/141781.html[/url]


[color=darkred]也可以这样[/color]

struts2 Action中获取request, response对象的方法

ActionContext ctx = ActionContext.getContext();        
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);

HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);

//ServletActionContext.APPLICATION;
//ServletActionContext.SESSION;
//ServletActionContext.PAGE_CONTEXT;