无拦截器

@CrossOrigin

一般情况下,直接用@CrossOrigin就可以搞定了

    @CrossOrigin(origins = "http://localhost:8080")
    @RequestMapping(value = "/cors", method = RequestMethod.GET)
    public Object cors(){
        ...
    }

JavaConfig

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/cors");
    }

}

有拦截器

比如需要对用户身份进行验证

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter{

    private static final Logger logger= LoggerFactory.getLogger(AuthInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String _authorization = request.getHeader("Authorization");
        logger.info("authorization:{}",_authorization);
        if(_authorization!=null){
            request.setAttribute("authorization",_authorization);
            return true;
        }else{
            response.setStatus(403);
            return false;
        }
    }

}

浏览器在发送OPTION请求时,可能(这个我还要去google一下)不会带上验证信息,在拦截器那里就没通过,进而结束请求.而前面方法的执行是在拦截器后面,不会起作用.(当然在拦截器那里判断,如果是OPTION方法就通过,也没问题)
这就需要另一种方法

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor);
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/cors", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}

这个过滤器会在执行拦截器前面执行


下载


TheViper
465 声望16 粉丝