这是一种安全策略,跨域:即只要协议名、域名、端口号中有一个不一样,就会被判定为是跨域请求。
创建filter类:
package cn.jiangdoc.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用拦截器拦截跨域请求
* @author jiangdoc
*
*/
public class SimpleCORSFilter implements Filter {
private boolean isCross = false;
@Override
public void destroy() {
isCross = false;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (isCross) {
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Max-Age", "0");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Accept, Cache-Control, Expires, Content-Type, X-E4M-With,token");
// 是否允许浏览器携带用户身份信息(cookie)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
}
// 跨域的图片上传会用到
//OPTIONS 方法发起一个预检请求,以检测实际请求是否可以被服务器所接受。
if( "OPTIONS".equals(httpServletRequest.getMethod())){
System.out.println("图片上传");
//状态码(204),指示请求成功,但没有要返回的新信息。
httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
}else{
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
}
}
在web.xml中配置:
<filter>
<filter-name>SimpleCORSFilterfilter-name>
<filter-class>cn.jiangdoc.web.filter.SimpleCORSFilterfilter-class>
<init-param>
<param-name>IsCrossparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>SimpleCORSFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
allow-credentials="true" />
mvc:cors>
如果在bean解析的时候出错:Cannot locate BeanDefinitionParser for element [cors]cvc-complex-type.2.4.c: 通配符的匹配无法找到元素 ‘mvc:cors’ 的声明。
1.检查springmvc的版本是不是4.2以上。
2.检查springmvc.xml中的约束文件的版本。
下面是我的:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
beans>
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
将该类注入到容器中:
<bean class="cn.jiangdoc.web.WebMvcConfigurerAdapter">bean>
下面是源码:
String[] DEFAULT_ORIGINS = { "*" };
String[] DEFAULT_ALLOWED_HEADERS = { "*" };
boolean DEFAULT_ALLOW_CREDENTIALS = true;
long DEFAULT_MAX_AGE = 1800;
可以看到该注解支持的类型和默认值。
使用方法只需要在controller层的类或方法上添加该注解并定义自己的想要的粒度。
例:
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
注解不起作用的原因:
1、是springMVC的版本要在4.2或以上版本才支持@CrossOrigin
2、非@CrossOrigin没有解决跨域请求问题,而是不正确的请求导致无法得到预期的响应,导致浏览器端提示跨域问题。
3、在Controller注解上方添加@CrossOrigin注解后,仍然出现跨域问题,解决方案之一就是:在@RequestMapping注解中没有指定Get、Post方式,具体指定后,问题解决。
推荐
在nginx的配置文件中:
server {
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
# add_header 'Access-Control-Max-Age' 3600;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 200;
}
}