单独使用基于拦截器的身份认证,在使用起来的时候不太方便,需要根据请求的url映射处理,参考这里。
为了改善这一情况,使用自定义注解+拦截器来完成身份认证。
新建一个自定义注解,级别应用在类和方法级别,并在运行时存在。
新建一个拦截器,在拦截其中获取注解,以判断是否需要身份认证。
首先,新建一个注解Authentication
package com.kye.annonation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 身份验证注解 * 可用于类和方法 * @author wg */ @Documented @Inherited @Target(value = { ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Authentication { /** * 是否需要进行身份验证,默认都需要验证 * * @return */ boolean validate() default true; /** * 身份认证参数名. * * @return */ String tokenName() default "token"; }
再新建一个拦截器LoginInterceptor
package com.kye.Interceptors; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.kye.annonation.Authentication; import com.kye.java.User; import com.kye.utils.Utils; public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod hand = (HandlerMethod) handler; Object target = hand.getBean(); Class<?> clazz = hand.getBeanType(); Method method = hand.getMethod(); if (clazz != null && method != null) { boolean isClzAnnotation = clazz.isAnnotationPresent(Authentication.class); boolean isMethondAnnotation = method.isAnnotationPresent(Authentication.class); Authentication auth = null; // 如果方法和类声明中同时存在这个注解,那么方法中的会覆盖类中的设定。 if (isMethondAnnotation) { auth = method.getAnnotation(Authentication.class); } else if (isClzAnnotation) { auth = clazz.getAnnotation(Authentication.class); } User user = Utils.getUserByToken(auth.tokenName()); if (user == null) { response.sendRedirect("/unlogin"); return false; } } } return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }
在springmvc.xml中配置映射根目录下所有url路径
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/" /> <bean class="com.kye.Interceptors.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>