一,访问request/session/application
如果在Action中,只需要往作用域中添加属性或者得到属性,就用以下的方法来得到:
ActionContext act = ActionContext.getContext();
act.put("username", "hwt");//向request中添加属性
act.get("username"); //取得request中的属性
act.getSession().put("username", "hwt");//向session中添加属性
act.getSession().get("username");//取得session中的属性
act.getApplication().put("username", "hwt");//向application中添加属性
act.getApplication().get("username");//取得application中的属性
如果需要得到request/session/application 对象的话,那么就用以下方法:
//得到Servlet容器
ServletContext sc = ServletActionContext.getServletContext();
//得到request对象
HttpServletRequest request = ServletActionContext.getRequest();
//得到response对象
HttpServletResponse response = ServletActionContext.getResponse();
//得到session对象
HttpSessionsession = request.getSession();
二,自定义拦截器
1,写一个实现类,继承Interceptor
2,在struts.xml中配置
如:权限的拦截
public class UserInterceptor implements Interceptor {
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation method) throws Exception {
HttpSession session = ServletActionContext.getRequest().getSession();
User user = (String) session.getAttribute("user");
if(user == null){
return "failure"; //拦截请求,转向输出一个result页面
}else {
method.invoke(); //允许进入方法
}
return null;
}
}
配置文件:
<package name="hwt" namespace="/hwt"extends="struts-default">
<interceptors>
<interceptor name="userIntercepter" class="hwt.Converter.UserInterceptor"/>
<! - - 定义拦截器栈,把默认的拦截器和自己写的拦截器结合起来 - - >
<interceptor-stackname="myStack">
<!—一定要加上defaultStack拦截器放在最后面-->
<interceptor-ref name="userIntercepter"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<action name="test" class="hwt.action.Demo1Action"method="show">
<!—如果把拦截器写在这个里面,那么进入这个Action后之后使用自己写的拦截器,不会使用默认的拦截器,但是默认的拦截器有很多强大的功能,如文件上传大小以及类型的控制,重复提交的控制等,所以我们在package中定义拦截器栈,放入系统的拦截器和自己写的拦截器-->
</action>
</package>
</struts>
如果希望包下的所有action都使用自定义的拦截器,可以通过<default-interceptor-ref name=“myIntercepterStack”/>,把拦截器定义为默认拦截器。
注意:每个包只能指定一个默认拦截器。另外,一旦我们为该包中的某个action显式指定了某个拦截器,则默认拦截器不会起作用。
默认的拦截器中的比较常用的拦截器:(后面会提到)
fileUpload
toKen
…