除此之外,为了能直接访问Servlet API,Struts2还提供了一个ServletActionContext工具类,这个工具类包含了如下几个静态方法:
方法 | 说明 |
static PageContext getPageContext( ) | 取得Web应用的PageContext对象 |
static HttpServletRequest getRequest( ) | 取得Web应用的HttpServletRequest对象 |
static HttpServletResponse getResponse( ) | 取得Web应用的HttpServletResponse对象 |
static ServletContext getServletContext( ) | 取得Web应用的ServletContext对象 |
借助于ServletActionContext类的帮助,开发者也可以在Action中访问Servlet API,并可避免Action类需要实现XxxAware接口---虽然如此,但该Action依然与Servlet API直接耦合,不利于高层次的解耦。
借助于ServletActionContext工具类的帮助,Action能以更简单的方式来访问Servlet API:
public class Login { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String execute(){ if(getUsername().equals("scott")&& getPassword().equals("tiger")){ HttpSession session=ServletActionContext.getRequest().getSession(); session.setAttribute("username",getUsername()); return "success"; } return "login"; } }