1,编写拦截器
- package com.jinhei.interceptors;
- import com.jinhei.utils.JwtUtils;
- import jakarta.servlet.http.HttpServletRequest;
- import jakarta.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
-
- import java.util.Map;
- @Component
- public class LoginInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- //请求头里面拿到令牌,令牌验证
- String token = request.getHeader("Authorization");
- // 验证token
- try {
- Map<String, Object> claims = JwtUtils.parseJWT(token);
- // 放行
- return true;
- } catch (Exception e) {
- // HTTP响应码 401
- response.setStatus(401);
- // 不放行
- return false;
- }
- }
- }
复制代码 2,配置并注册拦截器
- package com.jinhei.config;
-
- import com.jinhei.interceptors.LoginInterceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- //配置类注解
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
- @Autowired
- private LoginInterceptor loginInterceptor;
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // 注册拦截器,登录接口和注册接口不拦截
- registry.addInterceptor(loginInterceptor)
- .excludePathPatterns("/user/login","/user/register");
- }
- }
复制代码
JinheiNew.zip
(65.76 KB, 下载次数: 0, 售价: 50 金币)
|