您的位置:首页 > 编程语言 > Java开发

Struts2拦截器简单示例

2012-06-05 18:01 429 查看

一、定义拦截器

Struts2规定用户自定义拦截器必须实现com.opensymphony.xwork2.interceptor.Interceptor接口其中,init和destroy方法会在程序开始和结束时各执行一遍,不管使用了该拦截器与否,只要在struts.xml中声明了该拦截器就会被执行。intercept方法就是拦截的主体了,每次拦截器生效时都会执行其中的逻辑。不过,struts中又提供了几个抽象类来简化这一步骤。public abstract class AbstractInterceptor implements Interceptor;public abstract class MethodFilterInterceptor extends AbstractInterceptor;都是模板方法实现的。其中AbstractInterceptor提供了init()和destroy()的空实现,使用时只需要覆盖intercept()方法;而MethodFilterInterceptor则提供了includeMethods和excludeMethods两个属性,用来过滤执行该过滤器的action的方法。可以通过param来加入或者排除需要过滤的方法。一般来说,拦截器的写法都差不多。看下面的示例:
/**
* 自定义拦截器
* 功能:若用户已登录继续执行当前action,
*      否则返回登录页面
* @author zhezi
*
*/
@SuppressWarnings("serial")
public class AuthInterceptor extends AbstractInterceptor {

@Override
public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
if(session.getAttribute(Const.user) == null){
return Action.LOGIN;
}
String result = invocation.invoke();
return result;
}
}

二、声明拦截器

在struts中拦截器实际上分为拦截器和拦截器栈,拦截器栈可以包含一到多个拦截器或者拦截器栈。需将自定义拦截器加上struts缺省拦截器形成新的缺省拦截器。特别::需注意拦截器顺序,默认拦截器在上。

<interceptors>
<interceptor name="login" class="jp.struts.interceptor.AuthInterceptor"></interceptor>
<interceptor-stack name="myDefault">
<!-- 引用默认拦截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<!-- 引用自定义拦截器 -->
<interceptor-ref name="login"></interceptor-ref>
<interceptor-ref name="myInterceptor3">
<!--不拦截的方法-->
<param name="excludeMethods">test,execute</param>                                  <!--包含拦截的方法-->
<param name="includeMethods">test</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myDefault"></default-interceptor-ref>

三、定义全局result

因为全局定义了拦截器,虽然拦截器在通过拦截的情况下会返回特定Action的result,但有时候比如权限验证失败等情况下,自定义拦截器会返回自定义的结果,不属于任何特定Action,所以我们也需要定义一个全局result用以响应这个拦截器的返回值。
<global-results>
<result name="Exception">/common/exception.jsp</result>
<result name="RuntimeException">/common/runtime_exception.jsp</result>
<result name="login" type="redirect">/login.jsp</result>
</global-results>
本文出自 “兄弟无间” 博客,请务必保留此出处http://llwbrothers.blog.51cto.com/2360705/888676
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: