登陆拦截注解方式实现 springboot

1.由于长时间没用过注解,因此想做个记录,免得将来忘记。

  首先注解类:

  

import java.lang.annotation.*;

/**
 * @author 95831
 *
 * 登陆拦截
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Auth {
}

2.拦截器里面获取注解,如果注解不为空,说明该方法上面有注解,则需要执行注解的逻辑

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 95831
 * 登陆拦截
 */

public class AuthFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Auth auth = getAuth(o);
        if(auth != null) {

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private Auth getAuth(Object handler) {
        if(!(handler instanceof HandlerMethod)) {
            return null;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        return handlerMethod.getMethod().getAnnotation(Auth.class);
    }
}

3.向容器里面添加拦截器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author 95831
 * 添加注解
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public AuthFilter getAuthFilter() {
        return new AuthFilter();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getAuthFilter()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

此时整个拦截就可以实现了。

posted @ 2018-11-12 16:17  言灵之书  阅读(679)  评论(0编辑  收藏  举报