Struts2 访问 Servlet API 的三种方法

Struts2 相比 Struts1 而言,不用直接访问 Servlet API, 使得 Action 可以脱离 Web 容器进行测试。那么 Struts2 访问 Servlet API 有三种方式:

1.使用 ActionContext

  在程序中使用  ActionContext ac = ActionContext.getContext(); 获取到ActionContext的一个实例,然后使用ac.put("key", "value");将信息返回给Web前端。但使用该方法需要在Action类中实现request参数的setter()和getter()方法。如:在表单提交的数据中有username参数,则需要有setUsername()和getUsername()方法。

2.使用 ***Aware 接口

  将Action类实现该接口,然后通过该接口中的 setServletRequest(HttpServletRequest request) 方法获取到Servlet API。然后使用 request.setAttribute("key","value");将信息返回给Web前端。

3.使用 ServletActionContext 类

  使用该方法可以直接通过调用该类中的静态方法获取到 Servlet API。如,ServletActionContext.getRequest();

posted @ 2013-03-11 09:46  lihui_yy  阅读(3164)  评论(0编辑  收藏  举报