Java编写WEB后台接口,跨域问题的两种解决办法。

前言

本人一直从事前端开发,最近在学习使用SSM框架来写后台接口。一路跌跌撞撞,不知掉进坑里多少次,才看到一点希望!

问题

在前端向后台发送http请求,调试发现:

<-- Failed to load http://localhost:8080/ease/login.do: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.  -->

百度一搜,原来是跨域问题。

解决办法

第一种办法:使用Chrome的CORS插件,插件地址: 插件地址
https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog
在咱们天朝,对Google的各种屏蔽,没有翻墙工具,你是没办法下载该插件的。
第二种办法:自定义filter,设置response的Header。

//filter类
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String strUri = request.getRequestURI();
        System.out.println(strUri);
        if(strUri.indexOf("login.do") > -1 ) {
            response.setHeader("Access-Control-Allow-Origin", "*");
         };
         filterChain.doFilter(request, response);    
    }

}

然后在web.xml中加上:

 <filter>  
        <filter-name>corsFilter</filter-name>    
        <filter-class>com.ease.filter.CorsFilter</filter-class>    
    </filter>    
    <filter-mapping>    
        <filter-name>corsFilter</filter-name>    
        <url-pattern>*.do</url-pattern>    
    </filter-mapping>
  <filter>

这样问题就解决了!

猜你喜欢

转载自blog.csdn.net/Doniet/article/details/78823238