一、常量配置
1.struts.properties文件配置
key-value对
例:
###设置默认编码集为UTF-8格式
struts.i18n.encoding=UTF-8
###设置使用开发模式
struts.devMode=true
###设置默认的local为en_US
struts.local=en_US
2.web.xml文件配置
例: !!需放在<filter>标签下
<!--配置常量-->
<init-param>
<param-name>struts.i18n.encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
3.struts.xml文件配置
例:
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"/>
</struts>
二、Struts框架中访问Servlet API
1.通过ActionContext类访问 !!无法访问到其实例
ActionContext context=ActionContext.getContext();
context.put("name","tom"); //${requestScope.name}
context.getApplication().put("name","tom"); //${applicationScope.name}
context.getSession().put("name","tom"); //${sessionScope.name}
2.通过特定接口访问
(1)ServletRequestAware :实现该接口后,可直接访问HttpServletRequest实例
(2)ServletResponseAware :实现该接口后,可直接访问HttpServletResponse实例
(3)ServletContextAware :实现该接口后,可直接访问ServletContext实例
例:
public class LoginAction implements Action,ServletContextAware{
private ServletContext context;
public void setServletContext(ServletContext ctx){
context=ctx;
}
public String execute() throws Exception{
context.setAttribute("user","jim");
return SUCCESS;
}
}
3.通过ServletActionContext访问
该类常用方法:
(1)HttpServletRequest org.apache.struts2.ServletActionContext.getRequest() :获得HttpServletRequest对象
(2)HttpServletResponse org.apache.struts2.ServletActionContext.getResponse() :获得HttpServletResponse对象
(3)ServletContext org.apache.struts2.ServletActionContext.getServletContext() :获得ServletContext对象
三、ModelDriven接口
import com.model.XxMOdel;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class LoginAction extends ActionSupport implements ModelDriven<XxMOdel>{
private static final long serialVersionUID = 1L;
private XxMOdel user = new XxMOdel();
public XxMOdel getModel(){
return user;
}
public String execute() throws Exception{
ActionContext context=ActionContext.getContext();
context.put("user",user);
teturn SUCCESS;
}
}