Action訪問ServletAPI
struts2的一個重大改良之處就是與ServletAPI的解耦。不過,對于Web應用而言,不訪問ServletAPI幾乎是不可能的。例如跟蹤HTTPSession的狀態。Struts2框架提供了一種輕松的方式來訪問ServletAPI。通常需要訪問的對象是HttpServletRequest,HttpServletSession,ServletContext,這三類也代表了JSP的內置對象中的request,session,application.
方法有:
1 Object get(Object key):類似于條用HttpServletRequest的getAttribute(String name)
2 Map getApplication:返回對象為map,模擬了ServletContext。
3 Static ActionContext().getContext(),獲取ActionContext實例。
4 Map getParameters()
5 void setApplication(Map application)
6 void setSession(Map session)
用一個2方法,獲取ActionContext實例,通過該對象的getApplication()和getSession()的put(key,value)方法,實現訪問ServletAPI。
一個用ActionContext().getContext()獲取ServletContext的例子
index.jsp
雖然Struts2提供了ActionContext來訪問ServletAPI,但是并不能直接獲得ServletAPI的實例。但是Struts2提供了一下接口,
1 ServletContextAware:實現該接口的Action可以直接訪問ServletContext實例。
2 ServletRequestAware:實現該接口的Action可以直接訪問HttpServletRequest實例。
3 ServletResponseAware
例如
Action類
public class LoginAciton implements Action,ServletResponseAwre{
private HttpServletResponse response;
private String username;
private String password;
....//setter getter
public void serServletResponse(HttpServletResponse response){
this.response=response;
}
public String execute() throws Exception{
Cookie c = new Cookie("user",getUsername);
c.setMaxAge(60*60);
response.addCookie(c);
return SUCCESS;
}
}
//通過HttpServletResponse為系統添加Cookies對象。
jsp頁面
<body>
從系統中讀出Cooki值:${cookies.user.value}<br>
</body>
=======雖然可以在Action中獲得HttpServleResponse對象,但是希望通過它來生成服務器相應是不可能的。即使在Struts2中獲得了HttpServletResponse對象,也不要嘗試直接在Action中對客戶端生成相應。沒有任何實際意義。