springboot 跨域 请求处理

1.springboot的配置项

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

 

//    @Override
//    public void addCorsMappings(CorsRegistry corsRegistry){
//        /**
//         * 所有请求都允许跨域,使用这种配置就不需要
//         * 在interceptor中配置header了
//         */
//        corsRegistry.addMapping("/**")
//                .allowCredentials(true)
//                .allowedOrigins("*")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                .allowedHeaders("*")
//                .maxAge(3600);
//    }
}

2.拦截器中处理

添加拦截器

 @Autowired
    private AuthInterceptor authInterceptor;

//    @Override
//    public void addCorsMappings(CorsRegistry corsRegistry){
//        /**
//         * 所有请求都允许跨域,使用这种配置就不需要
//         * 在interceptor中配置header了
//         */
//        corsRegistry.addMapping("/**")
//                .allowCredentials(true)
//                .allowedOrigins("*")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                .allowedHeaders("*")
//                .maxAge(3600);
//    }


    /**
     * 添加自定义拦截器
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**")//拦截的访问路径,拦截所有
                .excludePathPatterns("/static/*")//排除的请求路径,排除静态资源路径
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/user/getUserInfo")
                .excludePathPatterns("/error")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
        ;
        super.addInterceptors(registry);
    }  

  拦截器处理

/**
 * TODO
 *
 * @author hs
 * @date 2020/12/28 15:47
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    GdUserService userService;
    @Autowired
    GdRoleService roleService;
    @Autowired
    GdAuthService authService;

    /**
     * 在整个请求结束之后被调用,DispatcherServlet 渲染视图之后执行(进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {

    }


    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     *
     * @return 返回true才会继续向下执行,返回false取消当前请求
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,userToken");
        response.setHeader("Access-Control-Expose-Headers", "*");

        if (request.getMethod().equals("OPTIONS")) {
//            returnJson(response,null );
            return true  ;

        }
  //鉴权业务逻辑
  //………………
return true ; } private void returnJson(HttpServletResponse response, String json) throws Exception{ PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); try { writer = response.getWriter(); writer.print(json); } catch (IOException e) { System.out.println("response error"+e.toString()); } finally { if (writer != null) writer.close(); } } }

  

上一篇:关于装饰模式的一次实践


下一篇:手把手教你做Unity中的FSM状态机(二)