一、访问或添加request/session/application属性
a) 通过ServletActionContext.类直接获取
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
b) 实现指定接口,由struts框架运行时注入
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
c) 获取ActionContext对象,使用该对象访问serletAPI
public String execute(){
//首先获取actionContext对戏那个,通过该对象访问setvletAPI
ActionContext context=ActionContext.getContext();
//模拟application对象存入值
context.getApplication().put("name", "marico");
//模拟session
context.getSession().put("pass", 123456);
//模拟request
context.put("sex", "男");
return SUCCESS;
}
二、文件上传
a) 把指定的jar加载到项目中,commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar
b) 把form表中的类型enctype设置为:“multipart/form-data
c) 在指定的Action类中添加对应的属性 属性名必须有规定 upload为自定义的表单中的name属性
private File uploadImage;//得到上传的文件
private String uploadImageContentType;//得到文件的类型
private String uploadImageFileName;//得到文件的名称
D)多个文件的上传实现
把需要得到的文件的属性变成数据或者list集合都可以实现,上传遍历就可以。
private File[] uploadImages;//得到上传的文件
private String[] uploadImagesContentType;//得到文件的类型
private String[] uploadImagesFileName;//得到文件的名称
三、拦截器的介绍
a) 使用拦截器可以实现横切功能并使这些实现相对action甚至Struts2框架保持独立。
b) 可以实现和使用自己所需的特性且不用修改框架的底层代码。
c) 使用拦截器可以达到以下目的:
i. 在调用Action之前,提供预处理逻辑
ii. 与Action进行交互,提供执行信息,比如设置请求中的参数
iii. 在调用Action之后,提供后处理逻辑
iv. 修改返回的结果,进而修改呈现给用户的内容
v. 捕获异常从而替换可执行的处理过程或返回一个不同结果
d) 配置一个内置struts2自带的拦截器
<action>
<interceptor-ref name="timer" />
<result>/success.jsp</result>
</action>
e) 实现自定义的拦截器,可以实现Interceptor该接口或者继承AbstractInterceptor这个类,可以重写的方法有三个:
i. init() 方法用来初始化拦截器
ii. destroy()方法为拦截器提供清理
iii. intercept(ActionInvocation invocation)方法为拦截器处理业务规则,参数就可以得到当前的action对象和作用域的对象。然后就可以实现自己需要拦截的内容了。当调用ivoke()方法后返回的结果就是action返回的结果一样,直接在struts.xml配置的name属性的值,它就会做指定的操作。
iv. 声明自定义的拦截器并加载到指定的action当中
<interceptors>
<interceptorname="UserCheckLog“ class="com.redarmy.intercepter.LoginInteceptor"></interceptor>
<!-- 定义拦截器的栈 -->
<interceptor-stack name="mystack">
<interceptor-ref name="MyTimer"></interceptor-ref>
<interceptor-ref name="UserCheckLogin"></interceptor-ref>
<!-- 添加Struts2默认拦截器的支持,否则struts以前的拦截器会失效 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>