=============================
Struts2 和 Servlet 耦合
=============================
首选 ActionConext 其次 ServletActionContext 最后是实现接口
-- 1 --
### ActionContext ### --- 不能获得response对象
static ActionContext getContext() 获得当前线程的向下文
相当于
Object get(Object key) ---- getAttribute()
void put( Object key, Object value ) ---- setAttribute()
Map getParameter() 相当于Servlet中的getParameterMap()
Map getApplication() 对应于ServletContext
如:
action中
ActionContext.getContext().put("zhangsan","hello");
jsp中
张三:${ requestScope.zhangsan }
-- 2 --
通过接口使用 --- 典型的依赖注入
### ServletContextAware ### 接口
void setServletContext( ServletContext )
### ServletRequestAware ### 接口
void setServletRequest( HttpServletRequest )
### ServletResponseAware ### 接口
void setServletResponse( HttpServletResponse )
例:
public class LoginAction extends ActionSupport
implements ServletRequestAware,
ServletResponseAware {
private String username;
private String password;
//setter...getter...
private HttpServletRequest request;
private HttpServletResponse response;
public String execute() throws Exception {
//使用request对象
request.setAttribute("zhangshan","hello");
//使用response对象
Cookie cookie = new Cookie("username",
this.getUsername());
cookie.setMaxAge(1000);
response.addCookie(cookie);
return "success";
}
//这个方法由Strust2框架来自动调用
//调用后,便可以使用容器的request对象了
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setServletResponse(HttpServletResponse responset) {
this.response = response;
}
}
---------------------
jsp页面中显示cookie
cookie: ${ cookie.username.value }
--------------------
-- 3 --
使用 org.apache.struts2.ServletActionContext类
---继承于 com.opensymphony.xwork2.ActionContext
内部全部为static的方法
static ActionContext getActionContext(HttpServletRequest req)
static PageContext getPageContext()
static HttpServletRequest getRequest()
static HttpServletResponse getResponse()
static ServletContext getServletContext()
static ValueStack getValueStack(HttpServletRequest req)
-----
static void setRequest(HttpServletRequest request)
static void setResponse(HttpServletResponse response)
static void setServletContext(ServletContext servletContext)
例:
public class LoginAction extends ActionSupport {
private String username;
private String password;
//setter...getter...
public String execute() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
return "success";
}
}