您的位置:首页 > 其它

利用自定义注解来配合使用SpirngMVC拦截器

2016-01-19 00:00 686 查看
对于注解的使用这里就不在多介绍,直接上代码了!

先新建一个注解文件:

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessRequired {
String value() default "";
}


然后再新建一个拦截器文件.这里我们实现的是HandlerInterceptor拦截器,关于该拦截器以及其他拦截器的知识,自己百度谷歌补充吧。

public class LoginInterceptor   implements HandlerInterceptor {

protected Logger log= Logger.getLogger(getClass());

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {

}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {

}

@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
AccessRequired annotation = method.getAnnotation(AccessRequired.class);
if(null != annotation){
String value = annotation.value();
if(value.length()==0){
return true;
}
String sessionValue = (String)req.getSession().getAttribute(value);
if(null != sessionValue){
return true;
}else{
log.warn("session.getAttribute("+value+") is null",new Exception("无权限登录 "));
resp.sendRedirect("login");
}
}
//没有注解通过拦截
return true;
}
}


3.配置SpringMVC的配置文件,springmvc.xml.

<!-- 	配置拦截器-->
<bean id="loginInterceptor" class="com.infowall.interceptor.LoginInterceptor"></bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/mvc/**"/>
<ref bean="loginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>


<mvc:interceptors>这个标签是用来配置拦截器的,使用mvc标签,需要在xml文件中添加mvc的schame

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd[/code] 
注意问题:

如果你使用了<mvc:resources mapping="/resources/**" location="/resources/" />来配置静态资源,那么配置如上拦截器的时候就要使用使用了全局拦截/**,否则会拦截静态资源抛出ResourceHttpRequestHandler cannot be cast to HandlerMethod异常.

办法一:加上拦截路径前缀

<mvc:mapping path="/path/**" />

<!-- 这里使用一个path前置,如api,否则会拦截静态资源 -->

办法二:在自定义拦截器中使用instanceof 过滤ResourceHttpRequestHandler 类型.

还有在写拦截器的时候,注意导入的class,

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


不然,导入错的类,也会包异常。

4.在你的controller的方法上,类上使用@@AccessRequired(value="查询的key")。

@RequestMapping("/success")
@AccessRequired(value="userName")
public String success(){
return "success";
}


提示:推荐能使用servlet规范中的过滤器Filter实现的功能就用Filter实现,因为HandlerInteceptor只有在Spring Web MVC环境下才能使用,因此Filter是最通用的、最先应该使用的。如登录这种拦截器最好使用Filter来实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: