服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - springboot实现拦截器之验证登录示例

springboot实现拦截器之验证登录示例

2020-08-18 11:33天使没吃饱 Java教程

本篇文章主要介绍了springboot实现拦截器之验证登录示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

整理文档,搜刮出一个springboot实现拦截器验证登录示例,稍微整理精简一下做下分享。

添加jar包,这个jar包不是必须的,只是在拦截器里用到了,如果不用的话,完全可以不引入

?
1
2
3
4
5
<dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.5</version>
    </dependency>

springboot默认为Tomcat,如果用jetty,还需要引入

?
1
2
3
4
5
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

1、以登录验证为例,首先创建个@Auth注解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.demo.interceptor;
 
import java.lang.annotation.*;
 
/**
 * Created by huguoju on 2016/12/30.
 * 在类或方法上添加@Auth就验证登录
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Auth {
}

2、创建一个Constants,在拦截器里用

?
1
2
3
4
5
6
7
8
9
10
11
package com.demo.util;
 
/**
 * Created by huguoju on 2016/12/30.
 */
public interface Constants {
  int MAX_FILE_UPLOAD_SIZE = 5242880;
  String MOBILE_NUMBER_SESSION_KEY = "sessionMobileNumber";
  String USER_CODE_SESSION_KEY = "userCode";
  String SESSION_KEY = "sessionId";
}

3、创建一个SessionData,用于保存在session中的字段

?
1
2
3
4
5
6
7
8
9
10
11
12
package com.demo.model;
 
import lombok.Data;
 
/**
 * Created by huguoju on 2016/12/30.
 */
@Data
public class SessionData {
  private Integer userCode;
  private String mobileNumber;
}

4、实现登录拦截实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.demo.interceptor;
 
import com.demo.model.SessionData;
import com.demo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
 
import static com.demo.util.Constants.MOBILE_NUMBER_SESSION_KEY;
import static com.demo.util.Constants.SESSION_KEY;
import static com.demo.util.Constants.USER_CODE_SESSION_KEY;
 
/**
 * Created by huguoju on 2016/12/30.
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
  @Autowired
  private RedisUtil redisUtils;
  private final static String SESSION_KEY_PREFIX = "session:";
  public boolean preHandle(HttpServletRequest request,
               HttpServletResponse response, Object handler) throws Exception {
    if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
      return true;
    }
    handlerSession(request);
 
    final HandlerMethod handlerMethod = (HandlerMethod) handler;
    final Method method = handlerMethod.getMethod();
    final Class<?> clazz = method.getDeclaringClass();
    if (clazz.isAnnotationPresent(Auth.class) ||
        method.isAnnotationPresent(Auth.class)) {
      if(request.getAttribute(USER_CODE_SESSION_KEY) == null){
  
         throw new Exception();
         
      }else{
        return true;
      }
    }
 
    return true;
 
  }
  public void handlerSession(HttpServletRequest request) {
    String sessionId = request.getHeader(SESSION_KEY);
    if(org.apache.commons.lang3.StringUtils.isBlank(sessionId)){
      sessionId=(String) request.getSession().getAttribute(SESSION_KEY);
    }
    if (org.apache.commons.lang3.StringUtils.isNotBlank(sessionId)) {
      SessionData model = (SessionData) redisUtils.get(SESSION_KEY_PREFIX+sessionId);
      if (model == null) {
        return ;
      }
      request.setAttribute(SESSION_KEY,sessionId);
      Integer userCode = model.getUserCode();
      if (userCode != null) {
        request.setAttribute(USER_CODE_SESSION_KEY, Long.valueOf(userCode));
      }
      String mobile = model.getMobileNumber();
      if (mobile != null) {
        request.setAttribute(MOBILE_NUMBER_SESSION_KEY, mobile);
      }
    }
    return ;
  }
}

5、配置拦截器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.demo.interceptor;
 
import org.hibernate.validator.HibernateValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
/**
 * Created by huguoju on 2016/12/30.
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.demo.controller")
@PropertySource(value = "classpath:application.properties",
    ignoreResourceNotFound = true,encoding = "UTF-8")
public class MvcConfig extends WebMvcConfigurerAdapter {
  private static final Logger logger = LoggerFactory.getLogger(MvcConfig.class);
  @Autowired
  LoginInterceptor loginInterceptor;
 
  /**
 
   * <p>
   *   视图处理器
   * </p>
   *
   * @return
   */
  @Bean
  public ViewResolver viewResolver() {
    logger.info("ViewResolver");
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
  }
 
  /**
   * 拦截器配置
   * @param registry
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 注册监控拦截器
    registry.addInterceptor(loginInterceptor)
        .addPathPatterns("/**")
     .excludePathPatterns("/configuration/ui");
 
  }
 
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOrigins("*")
        .allowedHeaders("*/*")
        .allowedMethods("*")
        .maxAge(120);
  }
 
  /**
   * 资源处理器
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    logger.info("addResourceHandlers");
    registry.addResourceHandler("/swagger-ui.html")
        .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
 
}

以上就完成了,测试时可以在LoginInterceptor里打断点,然后在controller上或者方法上添加@Auth注解,
controller上添加以后这个controller里所有请求都验证登录,在方法里添加只有请求这个方法时验证

?
1
2
3
@Auth
@RestController
public class TestController {  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/u011493599/article/details/53942757

延伸 · 阅读

精彩推荐