struts2自定义拦截器实例
JAVA开发多半会遇到Struts2吧,而struts2的拦截器是很重要的,那么今天就简单总结一下Strusts2的自定义拦截器:
struts.xml配置:
<!– struts2拦截器 –>
<package name=”struts2″ extends=”json-default”>
<interceptors>
<!– 自定义拦截器 –>
<interceptor name=”myinterceptor”
class=”com.rd.common.util.MyInterceptor”>
</interceptor>
<!– 自定义拦截器栈 –>
<interceptor-stack name=”myDefaultStack”>
<interceptor-ref name=”defaultStack”>
</interceptor-ref>
<interceptor-ref name=”myinterceptor”>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!– 将自定义拦截器栈设置默认的拦截器 –>
<default-interceptor-ref name=”myDefaultStack”>
</default-interceptor-ref>
<!– 定义全局Result –>
<global-results>
<!– 当返回login视图名时,转入/login.jsp页面 –>
<result name=”login_out”>/show_login.jsp</result>
</global-results>
</package>
注意:struts.xml中的拦截器配置好后,如果想使用拦截器,可以让那个文件夹继承该文件夹,即extends=”struts2”即可。
拦截器类定义:
package com.rd.common.util;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
@SuppressWarnings(“serial”)
public class MyInterceptor implements Interceptor {
@Override
public void destroy() {
System.out.println(“——-销毁了拦截器——-“);
}
@Override
public void init() {
System.out.println(“——初始化了拦截器——“);
}
@SuppressWarnings(“rawtypes”)
@Override
public String intercept(ActionInvocation arg0) throws Exception {
ActionContext ctx = arg0.getInvocationContext();
Map session = ctx.getSession();
Integer userId = (Integer) session.get(“userid”);
if (userId == null) {
ctx.put(“tip”, “您未登录,请重新登录!”);
return “login_out”;
}
return arg0.invoke();
}
}