10.action中访问web元素(access web elements)
取得Map类型request,session,application,真实类型HttpServletRequest,HttpSession,ServletContex的引用
1.前三者:依赖于容器( map类型)
2.前三者:IOC // 一般只用这种( map类型)
3.后三者:依赖于容器(真实类型)
4.后三者:IOC(真实类型)
第一种:
“`
public class LoginAction extends ActionSupport{
private Map request;
private Map session;
private Map application;
public LoginAction(){
request = (Map) ActionContext.getContext().get("request");
session = ActionContext.getContext().getSession();
application = ActionContext.getContext().getApplication();
System.out.println("LoginAction");
}
public String execute(){
request.put("r1","r1");
session.put("s1", "s1");
application.put("a1","a1");
return SUCCESS;
}
}
“`
第二种(常用):
public class LoginAction2 extends ActionSupport implements RequestAware,SessionAware,ApplicationAware
{
private Map<String, java.lang.Object> request;
private Map<String,java.lang.Object> session;
private Map<String,java.lang.Object> application;
// DI IOC
public String execute(){
request.put("r1", "r1");
session.put("s1", "s1");
application.put("a1", "a1");// 一般不用
return SUCCESS;
}
public void setRequest(Map<String, java.lang.Object> map) {
this.request=map;
}
public void setApplication(Map<String, java.lang.Object> map) {
this.session=map;
}
public void setSession(Map<String, java.lang.Object> map) {
this.application=map;
}
}
第三种(很少用):
// 可以忘记
public class LoginAction3 extends ActionSupport{
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
public LoginAction3(){
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
System.out.println("LoginAction");
}
public String execute(){
request.setAttribute("r1","r1");
session.setAttribute("s1", "s1");
application.setAttribute("a1","a1");
return SUCCESS;
}
}
第四种(不常用):
// IOC
public class LoginAction4 extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
public String execute(){
request.setAttribute("r1","r1");
session.setAttribute("s1", "s1");
application.setAttribute("a1","a1");
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
this.session = request.getSession();
this.application = session.getServletContext();
}
}
这四种的返回JSP页面是统一的:
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<h2>login.jsp</h2>
<s:property value="#request.r1"></s:property> | <%=request.getAttribute("r1")%><br />
<s:property value="#session.s1"></s:property> | <%=session.getAttribute("s1")%><br />
<s:property value="#application.a1"></s:property> | <%=application.getAttribute("a1")%><br />
<s:debug></s:debug>
</body>
</html>