对于注解的使用这里就不在多介绍,直接上代码了!java
先新建一个注解文件:web
@Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AccessRequired { String value() default ""; }
而后再新建一个拦截器文件.这里咱们实现的是HandlerInterceptor拦截器,关于该拦截器以及其余拦截器的知识,本身百度谷歌补充吧。spring
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.
api
<!-- 配置拦截器--> <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
spring-mvc
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
注意问题:session
若是你使用了<mvc:resources mapping="/resources/**" location="/resources/" />来配置静态资源,那么配置如上拦截器的时候就要使用使用了全局拦截/**,不然会拦截静态资源抛出ResourceHttpRequestHandler cannot be cast to HandlerMethod异常.mvc
办法一:加上拦截路径前缀app
<mvc:mapping path="/path/**" />ide
<!-- 这里使用一个path前置,如api,不然会拦截静态资源 -->post
办法二:在自定义拦截器中使用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来实现。