教务管理系统-Struct2注解使用拦截器(Interceptor)

来源:互联网 发布:python标准输入输出 编辑:程序博客网 时间:2024/04/29 13:24

在我的毕业设计——基于SSH的教务管理系统,做了一个简单的权限控制,通过控制Action来对三个角色管理员、教师、学生进行控制。打算通过使用拦截器进行过滤。

在系统设计之初,我计划尽量少使用配置文件,尽量使用注解,所以在使用Struct2的拦截器的时候也计划使用注解来实现。下面是我定义的拦截器:

package com.edu.interceptor;import org.apache.struts2.ServletActionContext;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;/** * 拦截器:权限控制 * * xukai 2016年5月18日下午4:43:11 */public class ActionInterceptor extends AbstractInterceptor {private static final Logger logger = LoggerFactory.getLogger(ActionInterceptor.class);/** *  */private static final long serialVersionUID = -5004702507890081515L;@Overridepublic String intercept(ActionInvocation arg0) throws Exception {String url = ServletActionContext.getRequest().getRequestURL().toString();if (url.contains("login")) {return arg0.invoke();}String actionName = arg0.getAction().getClass().getName();logger.info("MethodInceptor.getAction: " + actionName);// 获得身份String identity = (String) ActionContext.getContext().getSession().get("identity");// 拦截Actionif (actionName != null && ( actionName.equals("com.edu.action.UserAction")) {if (identity != null && identity.equals("admin")) {return arg0.invoke();}}if (actionName != null && (actionName.equals("com.edu.action.StudentAction"))) {if (identity != null && identity.equals("student")) {return arg0.invoke();}}if (actionName != null && (actionName.equals("com.edu.action.TeacherAction"))) {if (identity != null && identity.equals("teacher")) {return arg0.invoke();}}ServletActionContext.getRequest().setAttribute("msg", "您的权限不足!");return "error";}}
可以业务逻辑是通过获取身份,然后决定是否能访问某个Action。

在Action上进行注解标注:

@InterceptorRefs(value = {@InterceptorRef(value = "defaultStack"),@InterceptorRef(value = "actionInterceptor")})
发现这里的value竟然没有对应的值,在使用配置文件的时候,是在配置文件中定义的,但是我没有添加struct.xml文件,使用的是全注解,所有我百度查,是否可以在ActionInterceptor上面添加某个注解,达到标准此类事是一个拦截器,从而对应InterceptorRef中的value,这个value我猜测就是拦截器的ref-name。

最后还是没有办法,区服了,添加了structs.xml文件:

<package name="xk-default" extends="json-default, struts-default"><interceptors><!-- 配置自己定义的拦截器 --><interceptor name="actionInterceptor" class="com.edu.interceptor.ActionInterceptor"></interceptor><!-- 配置全局的拦截器栈,替换系统的拦截器栈 --><interceptor-stack name="MYSTACK"><interceptor-ref name="actionInterceptor"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><default-interceptor-ref name="defaultStack"></default-interceptor-ref></package>
我隐约在structs的源码哪里好像看到了,拦截器的加载是通过配置文件进行读入的,所以不能使用注解进行拦截器的标识。现在又找不到了,大神如果有办法解决的话,求指点。



0 0
原创粉丝点击