Struts 2中访问Servlet API的几种方法小结

来源:互联网 发布:java人机猜拳源代码 编辑:程序博客网 时间:2024/06/06 18:30

在Struts 2框架中,Action与Servlet API相分离,使得Action无法访问Servlet API,将不能使用session、application等。为了解决这个问题,Struts 2提供了如下几种方法:

1、使用ActionContext

Action运行期间所用到的数据都保存在ActionContext中,例如session、客户端提交的参数等,ActionContext是Action的一个上下文对象。

ActionContext actionContext = ActionContext.getContext();

通过如上方法创建actionContext对象,然后使用actionContext对象提供的一些方法来实现相应的功能。例如,调用getSession()方法可以获得HttpSession对象。但是,这种方法只能使用少部分的Servlet API。

2、实现相应的aware接口

在Action中实现如下的一些接口:

org.apache.struts2.util.ServletContextAware:实现该接口的Action可以访问ServletContext对象。

org.apache.struts2.interceptor.ServletRequestAware:实现该接口的Action可以访问ServletRequest对象。

org.apache.struts2.interceptor.ServletResponseAware:实现该接口的Action可以访问ServletResponse对象。

org.apache.struts2.interceptor.SessionAware:实现该接口的Action可以访问HttpSession对象。

看下面的例子:

package action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.struts2.interceptor.ServletRequestAware;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport implements ServletRequestAware{private String name;// 定义request对象private HttpServletRequest request;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String execute() throws Exception {HttpSession session = request.getSession();session.setAttribute("user", this.name);return SUCCESS;}// 继承并实现该方法@Overridepublic void setServletRequest(HttpServletRequest request) {this.request = request;}}

可以实现其中的某一个接口,也可以使用全部的接口。这种方法弊端是实现起来比较麻烦,既要实现接口,还要实现接口里的set方法。

3、使用ServletActionContext

ServletActionContet提供了一系列的静态方法,可以获得HttpServletRequest、HttpServletResponse等等,看下面的例子:

package action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String execute() throws Exception {HttpServletRequest request = ServletActionContext.getRequest();HttpSession session = request.getSession();session.setAttribute("user", this.name);return SUCCESS;}}

以上的三种访问Servlet的方式,由于第一种只能获取到request对象,不能获取到response;第二种,使用起来过于麻烦,而且必须要实现接口,耦合性大;第三种最为简单,代码量又少,这也是推荐使用的方法。

0 0