核心思想
1、ActionContext
HttpServletRequest getAttribute setAttribute
ActionContext get put
//ActionContext.getContext() 获取入口
ActionContext.getContext().put("key", "value");
2、ServletRequestAware
package com.test.action; public class LoginAction extends ActionSupport implements ServletRequestAware
{
private static final long serialVersionUID = -74906200993380354L;
private HttpServletRequest request; @SuppressWarnings("unchecked")
public String execute() throws Exception
{
if("james".equals(this.getUsername()) && "james".equals(this.getPassword())){
Map map = ActionContext.getContext().getSession();
//ActionContext.getContext() 获取入口
//ActionContext.getContext().put("james", "get from AcionContext");
request.setAttribute("chenkai", "from ServletRequestAware");
map.put("user", "james");
return "success";
}else {
this.addFieldError("username", "username or password is wrong");
return "failer";
}
} /*
* 实现 ServletRequestAware 接口 方法
* struts2 自动加载,【ioc 依赖注入的方式】 将与容器相关的request参数set到应用里
*/
public void setServletRequest(HttpServletRequest request) {
this.request = request;
} }
3、ServletResponseAware 与 Cookie 的使用
public class LoginAction extends ActionSupport implements ServletResponseAware
{
private HttpServletResponse response;
public String execute() throws Exception
{ Cookie cookie = new Cookie("name", "james");
cookie.setMaxAge(100);
response.addCookie(cookie);
return SUCCESS;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
username:${requestScope.username }<br>
password:${requestScope.password }<br>
Cookie:${cookie.name }
</body>
</html>
4、ServletActionContext
public String execute() throws Exception
{
HttpServletResponse response = ServletActionContext.getResponse();
Cookie cookie = new Cookie("name", "james");
cookie.setMaxAge(100);
response.addCookie(cookie);
return SUCCESS;
}
建议使用顺序
a) ActionContext 【首选】
b) ServletActionContext [如果需要使用reponse]
c) ServletRequestAware [必须实现接口]