大家平时在项目开发中遇到跨域问题是怎么解决的呢?

我相信有很多小伙伴就会回答:在Controller加上@CrossOrigin就可以啦!

但我们知道,在企业开发中,会有很多个controller,controller数量多也便于维护和查找控制层代码

那有没有一种方式能解决这种繁琐的问题呢?答案是肯定的!

下面介绍如何用JSONP解决跨域问题,哦不是用拦截器解决hh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.ruben.controller.interceptor;


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CrossOriginIntercept implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
response.setHeader("Access-Control-Allow-Headers", ((HttpServletRequest) request).getHeader("Access-Control-Request-Headers"));
//跨域时首先会发送一个option请求,这里我们给option请求直接返回正常状态
if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpStatus.OK.value());
return false;
}
return true;
}

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

}

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

}
}

然后如果是springboot项目,需要写个webconfig引入一下

1
2
3
4
5
6
7
8
9
10
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(crossOriginIntercept).addPathPatterns("/**").excludePathPatterns("/static/**");
}

}

如果是spring项目,需要在springmvc.xml中引入

1
2
3
4
5
6
7
<!-- 拦截器3  跨域问题 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.ruben.controller.interceptor.CrossOriginIntercept"></bean>
</mvc:interceptor>
</mvc:interceptors>

看到这里就有小伙伴想说了:就这?跨域问题就能解决了?

对没错!就这!当然还有其他的方式,比如用一个nginx反向代理,用上面提到的@CrossOrigin注解,用JSONP等等,但我还是喜欢拦截器这种方式,因为其好处有三:

一、一次配置,之后无忧

二、减轻前端工作压力,不用担心跨域问题