truts2在Action中如何访问request,session,application(即ServletContext)对象????
方式一:与Servlet API解耦的方式
可以使用struts2中提供的Map对象来访问HttpRequest,HttpSession和ServletContext对象,要获取这三个Map对象,可以使用com.opensymphony.xwork2.ActionContext类提供的静态方法
ActionContext ctx=ActionContext.getContext();
ctx.getApplication().put(“app”,”Application应用对
象”);//ServletContext放入app
ctx.getSession().put(“ses”,”session应用对象”);
ctx.put(“req”,”request对象”);
######:
上面的三个方法,仅相当与request,session,applicationsetAttribute(string,object)方法。
struts2中提供的Map对象来提供类似request,session,application内置对象的功能,这些内置对象只有内置对象的一小部分功能,它不依赖于servlet,所以是解耦合的!!!
方式二:与Servlet
API耦合的访问方式
也可以直接访问Servlet环境中的HttpRequest,HttpSession和ServletContext对象。通过ServletActionContext.类提供的静态方法直接获取:
HttpServletRequest request=ServletActionContext.getRequest();
ServletContext
context=ServletActionContext.getServletContext();
HttpSession session=request.getSession();
HttpServletResponse
response=ServletActionContext.getResponse();
方式三、实现相关接口
- public class BaseAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {
- private static final long serialVersionUID = 7620009925942346125L;
- ActionContext context = ActionContext.getContext();
- HttpServletRequest request;
- HttpServletResponse response;
- SessionMap session;
- //获取request,response,session方式一,非IoC方式,不用实现SessionAware, ServletRequestAware, ServletResponseAware
- //ActionContext context = ActionContext.getContext();
- //HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
- //HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
- //Map session = context.getSession();
- //SessionMap session = (SessionMap) context.get(ActionContext.SESSION);
- //获取request,response,session方式一,IoC方式,必须实现SessionAware, ServletRequestAware, ServletResponseAware
- public void setSession(Map map) {
- this.session = (SessionMap) map;
- }
- public void setServletRequest(HttpServletRequest request) {
- this.request = request;
- }
- public void setServletResponse(HttpServletResponse response) {
- this.response = response;
- }
- }