Action訪問ServletAPI
struts2的一個(gè)重大改良之處就是與ServletAPI的解耦。不過,對于Web應(yīng)用而言,不訪問ServletAPI幾乎是不可能的。例如跟蹤HTTPSession的狀態(tài)。Struts2框架提供了一種輕松的方式來訪問ServletAPI。通常需要訪問的對象是HttpServletRequest,HttpServletSession,ServletContext,這三類也代表了JSP的內(nèi)置對象中的request,session,application.
方法有:
1 Object get(Object key):類似于條用HttpServletRequest的getAttribute(String name)
2 Map getApplication:返回對象為map,模擬了ServletContext。
3 Static ActionContext().getContext(),獲取ActionContext實(shí)例。
4 Map getParameters()
5 void setApplication(Map application)
6 void setSession(Map session)
用一個(gè)2方法,獲取ActionContext實(shí)例,通過該對象的getApplication()和getSession()的put(key,value)方法,實(shí)現(xiàn)訪問ServletAPI。
一個(gè)用ActionContext().getContext()獲取ServletContext的例子
index.jsp
雖然Struts2提供了ActionContext來訪問ServletAPI,但是并不能直接獲得ServletAPI的實(shí)例。但是Struts2提供了一下接口,
1 ServletContextAware:實(shí)現(xiàn)該接口的Action可以直接訪問ServletContext實(shí)例。
2 ServletRequestAware:實(shí)現(xiàn)該接口的Action可以直接訪問HttpServletRequest實(shí)例。
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為系統(tǒng)添加Cookies對象。
jsp頁面
<body>
從系統(tǒng)中讀出Cooki值:${cookies.user.value}<br>
</body>
=======雖然可以在Action中獲得HttpServleResponse對象,但是希望通過它來生成服務(wù)器相應(yīng)是不可能的。即使在Struts2中獲得了HttpServletResponse對象,也不要嘗試直接在Action中對客戶端生成相應(yīng)。沒有任何實(shí)際意義。