跨域问题解决

如果是 spring 4.2 版本以上的跨域问题解决

@RestController
@RequestMapping("/account")
public class AccountController {

	@CrossOrigin
	@RequestMapping("/{id}")
	public Account retrieve(@PathVariable Long id) {
		// ...
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
	public void remove(@PathVariable Long id) {
		// ...
	}
}

It is also possible to enable CORS for the whole controller:

@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

	@RequestMapping("/{id}")
	public Account retrieve(@PathVariable Long id) {
		// ...
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
	public void remove(@PathVariable Long id) {
		// ...
	}
}

In this example CORS support is enabled for both retrieve() and remove() handler methods, and you can also see how you can customize the CORS configuration using@CrossOrigin attributes.

You can even use both controller and method level CORS configurations, Spring will then combine both annotation attributes to create a merged CORS configuration.

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

	@CrossOrigin(origins = "http://domain2.com")
	@RequestMapping("/{id}")
	public Account retrieve(@PathVariable Long id) {
		// ...
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
	public void remove(@PathVariable Long id) {
		// ...
	}
}

如以上代码中说明,直接使用注解就可以解决

我主要说 springmvc 4.1 以下版本的处理方式
在解决跨域问题是,显示服务端要添加允许的跨域的 域名地址

 /**
    * 设置是否允许跨域
    * @param request
    * @param response
    */
   public static void setOrign(HttpServletRequest request,
                                  HttpServletResponse response) {
      System.out.println("innnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
      //允许跨域
      response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,"
            + " X-E4M-With,appId,token,userId");
      //配置文件中获取那些地址允许跨域请求
      String allowOrigin = getValue("allowOrigin");//配置文件中获取http://ac.96.com,https:dc.96.om
      String setOrigin = "";
      if(RString.isNotBlank(allowOrigin) && !"*".equals(allowOrigin)){
         String originHeader=request.getHeader("Origin");
         String []  allowDomain= allowOrigin.split(",");
         Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain));
         if(null !=  allowedOrigins && allowedOrigins.size() > 0 && allowedOrigins.contains(originHeader)){
            setOrigin = originHeader;
         }
      }else{
         setOrigin = allowOrigin;
      }
      response.setHeader("Access-Control-Allow-Origin", setOrigin);
      response.setHeader("Access-Control-Max-Age", "86400");//设置浏览器发送预检请求的有效时间  第一次会发送,在有效时间内不会再次发起

      //response.setHeader("Access-Control-Allow-Methods", "PUT,GET,POST,DELETE,OPTIONS");
   }

以上方法添加在拦截器中。
解决了一般的GET请求 跨域问题。
然后前端在请求头中 添加了一些自定义的请求头信息,问题就来了。

这里写图片描述

查看请求
这里写图片描述

第一次请求是 options请求方式 第二次 才是我代码中的 get 请求方式
但是我打断点在业务代码中,发现断点进不去,所有觉得应该是options请求都没有到服务端,或者是被拦截了。网上查找资料,发现org.springframework.web.servlet.DispatcherServlet 默认是不允许options 请求方式的,如果要允许该请求,需要自己设置
如下

	<servlet>
		<servlet-name>actionSpringMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring/spring-action-config.xml</param-value>
		</init-param>
		<init-param>  
            <param-name>dispatchOptionsRequest</param-name>  
            <param-value>true</param-value>  
        </init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

设置好了之后,发现OK了。请求都可以通了。
但是还有一个问题就是options 请求也会处理到业务逻辑里面。
这样就有问题了。如果服务端的接口的结果不是幂等的。那这样是有问题的。
所以必须允许options请求,同时又不处理业务请求

所以还是在拦截器中处理

 public static boolean isAllowMsg(HttpServletRequest request,
                                  HttpServletResponse response) {
      String m = request.getMethod();
      if("options".equalsIgnoreCase(m)){
         return false;
      }
      return true;
   }

拦截器中判断,如果请求方式 是 options 直接放回false 不请求业务代码了。

于是乎 就搞定了。

springboot 项目,解决跨域问题也可以

第一种

@Override
	public void addCorsMappings(CorsRegistry registry) {
		// TODO Auto-generated method stub
		registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*");
	}

这种方式不推荐,不嫩给解决 拦截器里面的跨域问题,
如果拦截器里面直接返回,就会出现跨域问题。

解决拦截器里面的跨域问题,用下面的方式,能解决

  @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 设置允许跨域请求的域名
        config.addAllowedOrigin("*");
        // 是否允许证书 不再默认开启
         config.setAllowCredentials(true);
        // 设置允许的方法
        config.addAllowedMethod("*");
        // 允许任何头
        config.addAllowedHeader("*");
        config.addExposedHeader("token");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值