Struts2获取request、session、application的三种方法

来源:互联网 发布:mac系统下gem安装sass 编辑:程序博客网 时间:2024/06/06 03:57

1、使用ActionContext访问Servlet API

      Struts2提供了一个ActionContext类,该类被称为Action上下文或者Action环境,Action可以通过该类来访问最常用的Servlet API。

①、getContext():静态方法,获取当前的ActionContext对象。

②、getSession():返回一个Map对象,该对象模拟了session作用域。

③、getApplication:返回一个Map对象,该对象模拟了Application作用域。

④、get(String key):对该方法传入“request”参数,即可返回一个Object对象,该对象模拟了request作用域。

⑤、getParameters():返回一个Map对象,该对象中保存了浏览器上传的参数。

特点:作用域都是由Action自己获取的,获取对象和使用对象的代码放在一个类中。

public class UserAction extends ActionSupport {private User user;public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String Login(){HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get("request");request.setAttribute("username", user.getUserName());
//也可以转Map哦//Map<String,Object> request2 = //    (Map<String, Object>) ActionContext.getContext().get("request");      //request2.put("username", user.getUserName());
return "success";}}

2、以IoC的方式访问Servlet API

      Action类中只保留使用这些对象的代码,而获取对象的代码由Struts2来实现。

public class UserAction extends ActionSupport implements RequestAware,SessionAware,ApplicationAware {private Map<String, Object> request;private Map<String, Object> session;private Map<String, Object> application;public void setApplication(Map application) {this.application = application;}public void setSession(Map session) {this.session = session;}public void setRequest(Map request) {this.request = request;}public String Login(){//转换成HttpServletRequest,根据需要来HttpServletRequest req=(HttpServletRequest)request;String name = req.getParameter("username");req.setAttribute("username", "张三");return "success";} }
       在上面代码中,Action实现了 RequestAware,SessionAware,ApplicationAware接口,这样Struts2就可以为Action注入request、session、application对象了。

以session为例,Struts2取得session对象,当UserAction被创建时,Struts2会判断UserAction是否实现了SessionAware接口,若实现,就会调用UserAction的setSession()

方法,并把session作为参数传入该方法。该方法的"this.session = session;"代码会把session保存为一个成员变量,这样就实现了session对象注入。


3、以耦合方式访问Servlet API

      即ServletActionContext类,这个类继承了ActionContext类,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:
(1)javax.servlet.http.HttpServletRequest : HTTPservlet请求对象
(2)javax.servlet.http.HttpServletResponse : HTTPservlet相应对象
(3)javax.servlet.ServletContext : Servlet上下文信息
(4)javax.servlet.jsp.PageContext : Http页面上下文

ServletActionContext源码:

package org.apache.struts2;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.util.ValueStack;import org.apache.struts2.dispatcher.mapper.ActionMapping;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.jsp.PageContext;import java.util.Map;/** * Web-specific context information for actions. This class subclasses <tt>ActionContext</tt> which * provides access to things like the action name, value stack, etc. This class adds access to * web objects like servlet parameters, request attributes and things like the HTTP session. */public class ServletActionContext extends ActionContext implements StrutsStatics {    private static final long serialVersionUID = -666854718275106687L;    public static final String STRUTS_VALUESTACK_KEY = "struts.valueStack";    public static final String ACTION_MAPPING = "struts.actionMapping";    @SuppressWarnings("unused")    private ServletActionContext(Map context) {        super(context);    }    /**     * Gets the current action context     *     * @param req The request     * @return The current action context     */    public static ActionContext getActionContext(HttpServletRequest req) {        ValueStack vs = getValueStack(req);        if (vs != null) {            return new ActionContext(vs.getContext());        } else {            return null;        }    }    /**     * Gets the current value stack for this request     *     * @param req The request     * @return The value stack     */    public static ValueStack getValueStack(HttpServletRequest req) {        return (ValueStack) req.getAttribute(STRUTS_VALUESTACK_KEY);    }    /**     * Gets the action mapping for this context     *     * @return The action mapping     */    public static ActionMapping getActionMapping() {        return (ActionMapping) ActionContext.getContext().get(ACTION_MAPPING);    }    /**     * Returns the HTTP page context.     *     * @return the HTTP page context.     */    public static PageContext getPageContext() {        return (PageContext) ActionContext.getContext().get(PAGE_CONTEXT);    }    /**     * Sets the HTTP servlet request object.     *     * @param request the HTTP servlet request object.     */    public static void setRequest(HttpServletRequest request) {        ActionContext.getContext().put(HTTP_REQUEST, request);    }    /**     * Gets the HTTP servlet request object.     *     * @return the HTTP servlet request object.     */    public static HttpServletRequest getRequest() {        return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);    }    /**     * Sets the HTTP servlet response object.     *     * @param response the HTTP servlet response object.     */    public static void setResponse(HttpServletResponse response) {        ActionContext.getContext().put(HTTP_RESPONSE, response);    }    /**     * Gets the HTTP servlet response object.     *     * @return the HTTP servlet response object.     */    public static HttpServletResponse getResponse() {        return (HttpServletResponse) ActionContext.getContext().get(HTTP_RESPONSE);    }    /**     * Gets the servlet context.     *     * @return the servlet context.     */    public static ServletContext getServletContext() {        return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT);    }    /**     * Sets the current servlet context object     *     * @param servletContext The servlet context to use     */    public static void setServletContext(ServletContext servletContext) {        ActionContext.getContext().put(SERVLET_CONTEXT, servletContext);    }}


eg:

public class UserAction extends ActionSupport{private HttpServletRequest request;public String Login(){request = ServletActionContext.getRequest();//request的获得必须在具体的方法中实现  String name = request.getParameter("username");request.setAttribute("username", "张三");return "success";} }

ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象.
注意:在使用ActionContext时有一点要注意: 不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req = ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,在ActionContext类中actionContext对象的创建为:  static ThreadLocal actionContext = new ActionContextThreadLocal(),ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的。ActionContext是线程安全的,而ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、query()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。 

 

阅读全文
0 0
原创粉丝点击