ajax跨域请求(CORS实现)

场景:目前有项目A(基于servlet的WEB项目),和项目B(基于spring boot的WEB项目),使用同一CAS提供单点登录,现在需要两个项目互相调用接口数据,所以涉及到ajax的跨域请求

调研:经过调研发现目前的ajax跨域解决方案有两种,jsonp和cors,其中jsonp需要在返回值中携带回调函数,cors则需要在响应头中附加指定参数。比对实现方式和优劣点,决定使用cors来实现

CORS原理:服务器在收到请求之后,在响应参数中加入,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Max-Age,Access-Control-Allow-Headers,Access-Control-Allow-Credentials等参数,浏览器在接收到返回值后会通过这些参数的设置来判断服务器是否支持跨域请求。所以,使用cors的方法就是通过设置过滤器,在指定请求的响应头中添加参数即可,传统的WEB项目,需要在web.xml中设置,而spring boot项目可以通过注解来设置

1,servlet的WEB项目实现CORS

服务器端新建过滤器类

package com.tas.util;

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.HttpServletResponse;

/**
 * 跨域支持

 */

public class SimpleCORSFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost");
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
		httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		// 是否支持cookie跨域
		httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}

在web.xml中配置过滤器,注意过滤器要配置在sevrlet和cas的过滤器之前


        Simple CORSFilter
        com.tas.util.SimpleCORSFilter


        Simple CORSFilter
        /*

这样的配置就完成了,需要注意的是,在需要跨域访问该项目的网页中,如果需要传递cookie,则要在ajax中打开withCredentials,如下

    $.ajax({
            url:"http://localhost:8080/tasociety/IndexController.crossdomainTest.do",
            type: "get",
            dataType:"json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
            	 alert("12345");
                 console.log(data);
               
            }
        })

2,spring boot 的WEB项目实现CORS

因为有默认的注解@CrossOrigin,所以直接配置在controller上就好了

package com.castmember.Controller;

@CrossOrigin(origins = "http://localhost:8080",allowCredentials = "true")
@Controller
public class IndexController {


	 @Autowired
	SysUserDao sysuserdao;

	@RequestMapping("/")
    public String index(Model model) {

		Optional useropt= sysuserdao.findById((long)1);
		model.addAttribute("user", useropt.orElse(null));
        return "index";
    }
}

在需要跨域访问该项目的网页中,如果需要传递cookie,则要在ajax中打开withCredentials,如下

   $.ajax({
            url:"http://localhost/castmember/crossdomaindata",
            type: "get",
            dataType:"json",
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success:function (data) {
            	 alert("12345");
                 console.log(data);
               
            }
        })

 

你可能感兴趣的:(java)