1.通过IOC方式直接访问Servlet API
在Struts2中,通过,Ioc方式将Serlvet对象注入到Action中,具体实现是一组接口觉得,要采用Ioc方式,必须在Action中实现一下接口:
ApplicationAware :以Map类型向Action中注入保存在ServletContext中的Attribute集合。
SessionAware: 以Map类型向Action注入保存在HttpSerssoin中的Attribute集合
CookiesAwate:以Map类型向Action中注入Cookie中的数据集合。
ParameterAware:向Action中注入请求参数集合。
1.action
package com.sh.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class IocAction extends ActionSupport implements ServletRequestAware{
private HttpServletRequest request;
private String loginName;
private String loginPassword;
private String message;
public String checkLogin(){
HttpSession session=request.getSession();
session.setAttribute("login", this.loginName);
return SUCCESS;
}
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
}
// get set
}
strust.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="iocAction" class="com.sh.action.IocAction" method="checkLogin">
<result name="success">/success.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
login.jsp
<body>
<center>
<h3>
<s:text name="loginTitle"/>
${popedom}
${error}
</h3>
<s:form action="iocAction" method="post">
<s:textfield name="loginName" label="loginName" />
<s:textfield name="loginPassword" label="loginPassword"/>
<s:submit label="loginBtn" />
<s:token/>
</s:form>
</center>
</body>
success.jsp
<body>
读取session中的信息:${sessionScope.login}
读取application中的信息:${applicationScope.login}
</body>
2.采用非IOC直接访问Servlet API
除了ActionContext 类。Struts2还提供了名称为ServletActionContext的辅助类来获取Servlet API,这是非IOC的方式,其静态方法有,getPageContext(),getRequest(),getResponse,getServletContext().
package com.sh.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class noIocAction extends ActionSupport{
private String loginName;
private String loginPassword;
private String message;
public String checkLogin(){
HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session=request.getSession();
session.setAttribute("login", this.loginName);
return SUCCESS;
}
//get set
}
其他的和上面一样