struts2自定义拦截器的创建方式
struts2自定义创建方式一
拦截器的的生命周期是随着程序的开始而创建 随着程序的结束而销毁
public class MyIntercept1 implements Interceptor{
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation arg0)
throws Exception {
return null;
}
@Override
public void destroy() {
}
}
2.struts2自定义拦截器创建方式二
public class Myintercept2 extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation arg0)
throws Exception {
return null;
}
}
3.struts2自定义拦截器创建方式三(常用方式)
public class MyIntercept3 extends MethodFilterInterceptor{
@Override
protected String doIntercept(ActionInvocation invocation)
throws Exception {
System.out.println("前处理");
String result = invocation.invoke();
System.out.println("后处理");
return result;
}
}
struts2自定义拦截器的配置
1.struts2自定义拦截器和全局异常处理的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="inner" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="MyIntercept"
class="com.xxx.intercept.MyIntercept"></interceptor>
<interceptor-stack name="myStack">
<interceptor-ref name="MyIntercept">
<param name="excludeMethods">add,update</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<global-results>
<result name="tologin" type="redirect">/hello.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error"
exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<action name="Demo01Action_*"
class="com.xxx.intercept.Demo01Action" method="{1}">
<result name="success">/hello.jsp</result>
<result name="error">/hello.jsp</result>
</action>
<package>
</struts>
struts2拦截器实现登录检查
1.创建自定义拦截器
public class MyInterceptor extends MethodFilterInterceptor{
@Override
protected String doIntercept(ActionInvocation invocation)
throws Exception {
// 根据session域中 是否存放了User对象
// 来判断 用户是否登录了
Object object = ActionContext.getContext().getSession().get("user");
if (object == null) {
// 没登录 重定向到登录页面
return "tologin";
} else {
// 登录了放行
return invocation.invoke();
}
}
}
2.在登录页面(login.jsp)显示登录失败的信息
<%@ taglib uri="/struts-tags" prefix="s" %>
<font color="red">
<s:property value="exception.message"/>
</font>
<s:debug></s:debug>