`

springboot 设置跨域

 
阅读更多

 

首先我们配置上host映射

前端:

 index.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<script th:src="@{/js/jquery.min.js}"></script>
<body>
<h1 th:text="${port}">Hello World</h1>
<button  id="button-click">Button</button>
<script>
    $(function(){
        $("#button-click").click(function(){
            $.ajax({
                url : "http://myproject.dev.cn:8080/sayHello",
                //url : "/sayHello",
                type : "POST",
                beforeSend: function(request) {
                    request.setRequestHeader("token","zzz");
                },
                success: function(result) {
                    alert(result);
                }
            })
        })
    })
</script>
</body>
</html>

 

此时访问 localhost:8080/index  然后点击 点击button 按钮就会看到有跨域的错误信息提示

因为我们的浏览器的域名是localhsot, 而我们请求的是 myproject.dev.cn 所以存在跨域问题。

 

yml 增加跨域的域名信息

cors:
  allowedOrigin: localhost

 

 

增加跨域过滤器

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;

public class AllowCrossDomainFilter implements Filter {

    @Value("${cors.allowedOrigin}")
    private String allowedOrigin;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println(" 跨域配置  >  allowedOrigin : " + allowedOrigin);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        System.out.println("访问url为: " + req.getRequestURI());
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        String origin = req.getHeader("Origin");
        if (StringUtils.isNotBlank(origin)) {
            URI uri = URI.create(origin.trim());
            String host = uri.getHost();
            System.out.println("origin : " + origin + " host: " + host + " > > allowedOrigin : " + allowedOrigin + " allowedOrigin.indexOf(host) : " + allowedOrigin.indexOf(host));
            if (allowedOrigin.indexOf(host) >= 0) {
                System.out.println(req.getRequestURI() + "允许跨域访问 > allowedOrigin : " + allowedOrigin);
                resp.addHeader("Access-Control-Allow-Origin", origin);
            }
            resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.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,userId,token");
            resp.setCharacterEncoding("utf-8");
        }
        filterChain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}

 

 

增加配置信息,吧过滤器加入过滤链

import com.example.springboot.filter.AllowCrossDomainFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {

    @Bean
    public FilterRegistrationBean filterOneRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(allowCrossDomainFilter());
        registration.addUrlPatterns(new String[]{"/*"});
        registration.setName("filterOne");
        registration.setOrder(1);
        return registration;
    }

    @Bean
    public AllowCrossDomainFilter allowCrossDomainFilter() {
        return new AllowCrossDomainFilter();
    }
}

 

此时在访问localhost:8080/index。然后点击button按钮,就可以看到已经可能访问了

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics