struts2 自定义拦截器 基础一案例 (登录权限)
下拦截器的功能如下,限制没有登录的用户进入访问页面.
使用分以下几步骤:
1. 编写自定义拦截器类:
public class ManagerIntercept extends AbstractInterceptor {
//重写拦截方法
public String intercept(ActionInvocation invocation) throws Exception {
??ActionContext context = invocation.getInvocationContext();
??String user = (String) context.getSession().get("user");
?
??? if (StringUtil.isNotNull(user)) {
????? ?return invocation.invoke();
????}
??? context.put("notLogin", "请先登录系统,再执行此操作.");
??? ?return Action.ERROR;
??? }
}
?
2. 于struts.xml文件中配置使用.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
??? "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
??? "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
?<!-- 配制国际化资源文件-->
?<constant name="struts.custom.i18n.resources"
??value="messageResource">
?</constant>
?
?<!-- 配制请求编码(request) -->
?<constant name="struts.i18n.encoding" value="UTF-8"></constant>
?
?<!-- 配置每交启动重新读取文件 -->
?<constant name="struts.i18n.reload" value="true"></constant>
?
?<!-- 配置基本的登录请求 -->
?<package name="userManagerAction" extends="struts-default">
?
??<!-- 配制拦截器 -->
??<interceptors>
???<interceptor name="authority"
????/>
?
??<!-- 配制全局的result页面? -->
??<global-results>
???<result name="error">/error.jsp</result>
???<result name="login">/login.jsp</result>
??</global-results>
?
??<!-- 配制基本的请求处理action -->
??<action name="login" method="login"
???exception="Exception">
???</exception-mapping>
??</action>
?</package>
</struts>
?
此包下的所有请求处理都将被拦截于action处理方法前.
?
----------------------------完,开发经验,以供后续开发使用与交流.-------------------------------
---------------------------------------------------尹当