1、Action对ServletAPI的访问有两种方式,分别是间接访问和直接访问。
2、使用ServletActionContext访问Servlet API
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext application = ServletActionContext.getServletContext();
PageContext pageContext = ServletActionContext.getPageContext();
Map<String, Object> session = ServletActionContext.getContext().getSession();
3、Action直接访问Servlet API,也就是注入方式
Struts2提供了如下几个接口使Action可以直接访问到Servlet API:
3.1:ServletContextAware:实现该接口的Action可以直接访问Web应用的ServletContext实例
3.2:ServletRequestAware:实现该接口的Action可以直接访问Web应用的ServletRequest实例.
3.3:ServletResponseAware:实现该接口的Action可以直接访问Web应用的ServletRsponse实例.
3.4:SessionAware实现该接口的Action可以直接访问Web应用的Map Session实例.
public class ContextAction02 extends ActionSupport
implements ServletRequestAware, ServletResponseAware, ServletContextAware, SessionAware{
HttpServletRequest request;
HttpServletResponse response;
Map sessionMap;
ServletContext sc;
public String test(){
System.out.println("ContextAction *********** test()");
request.setAttribute("username", "username_request");
sessionMap.put("username", "username_session");
sc.setAttribute("username", "username_application");
return "attr";
}
public void setSession(Map<String, Object> session) {
this.sessionMap = session;
}
public void setServletContext(ServletContext context) {
this.sc = context;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
4、通过ActionContext 访问
ActionContext有以下方法,将ServletAPI封装成Map集合了
// 创建一个ActionContextduixang
ActionContext context=ActionContext.getContext();
通过context对象获取Servlet API
// ActionContext有以下方法
Map<String,Object> getApplication()// 获取application
Map<String,Object> getParameters() //相当于 request.getParameterMap();
Map<String,Object> getSession(); //获取session
put(String key,Object value); //相当于request.setAttribute();
Object get(String key) //相当于request.getAttribute();
public class UserAddAction extends ActionSupport {
private String userName;
private String password;
@Override
public String execte() throws Exception {
ActionContext ac = ActionContext.getContext();
ac.getApplication.put("uname", userName);
ac.getApplication.put("upwd", password);
return SUCCESS;
}
}