SpringBoot实现前端请求拦截器
参考文档:https://blog.csdn.net/a14654/article/details/110383829
一、编写自定义拦截器:
package com.example.demo.loginInterceptor; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; public class PermissionInterceptor implements HandlerInterceptor { //controller层之前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //从请求头中获取所需参数 String token = request.getHeader("Authorization"); System.out.println("打印Token = " + token); boolean isHavePermission = (token != null); //返回 true,放行 false,拦截 if (isHavePermission) { System.out.println("权限检查通过::操作放行"); return true; } else { //设置response,手动返回response响应 response.setContentType("application/json;charset=utf-8"); Map<String, Object> error = new HashMap<>(); error.put("code", 70001); error.put("msg", "无访问权限"); error.put("data", "权限检查失败::当前用户没有该权限"); Gson gson = new GsonBuilder().create(); response.getWriter().print(gson.toJson(error)); System.out.println("拦截不通过"); //设置response,手动返回response响应 return false; } } }
二、将编写的自定义拦截器,加入到拦截系统中:
package com.example.demo.loginInterceptor; 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.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Bean public PermissionInterceptor permissionInterceptor() { return new PermissionInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(permissionInterceptor()) //.excludePathPatterns("/permission/get") //添加拦截路径 /** :拦截所有路径 .addPathPatterns("/**"); } }