SprintBoot解决跨域问题

2023-05-24 00:47:30 浏览数 (1)

代码语言:javascript复制
方法一:直接在Controller中添加注解@CrossOrigin
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
  //doSomething
}

代码语言:javascript复制
方法二:添加拦截器 
@Component
public class CrossOriginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader("Origin");
        if (origin == null || origin.equals("")) {
            return true;
        }
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
        response.setHeader("Access-Control-Allow-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "content-type");
        return true;
    }

    @Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

//将CrossOriginInterceptor注入到拦截器内
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 跨域拦截器(CrossOriginInterceptor)
      registry.addInterceptor(new CrossOriginInterceptor()).addPathPatterns("/**");
        // 注册 Sa-Token 拦截器,打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
    }
}

0 人点赞