如何在Spring Restfull WebService中正确启用CORS?

时间:2015-09-15 13:37:31

标签: json web-services spring-mvc cors

我想要实现的是在另一个域中使用我的spring restful web服务,但是当我执行生成JSON值的json url时,我的javascript控制台会生成此错误:

  

阻止跨源请求:同源策略禁止在http://localhost:8080/SpringServiceJsonSample/service/updatepool/1读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin')。   跨源请求已阻止:同源策略禁止在http://localhost:8080/SpringServiceJsonSample/service/updatepool/1读取远程资源。 (原因:CORS请求失败)。

以下是这些链接http://localhost:8080/SpringServiceJsonSample/service/updatepool/1

生成的JSON值
  

{ “参数userid”:1, “名字”: “品牌”, “姓氏”: “本尼特”, “电子邮件”: “benjie@gmail.com”}

这是我的SpringController.java:

@RestController
@RequestMapping("/service/updatepool/")
public class SpringServiceController {

    UserService userService = new UserService();

    @RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
    public User getUser(@PathVariable int id) {
        User user=userService.getUserById(id);
        return user;
    }
}

然后我创建了基于SimpleCORSFilter的spring.io教程,所以这里是我的SimpleCORSFilter.java类

@Component
public class SimpleCORSFIlter implements Filter{

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}
}

以下是我如何使用JSON值,首先我创建了看起来像的index.html文件 的index.html

<html ng-app>
<head>
<title>Angular Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
    <div ng-controller="Hello">
        <p>User ID : {{greeting.userid}}</p>
        <p>firstName : {{greeting.firstName}}</p>
        <p>lastName : {{greeting.lastName}}</p>
        <p>email : {{greeting.email}}</p>

    </div>
</body>
</html>

这是我的app.js

function Hello($scope, $http) {
    $http.get('http://localhost:8080/SpringServiceJsonSample/service/updatepool/1').
        success(function(data) {
            $scope.greeting = data;
        });
}

我已经创建了CORS过滤器类,为什么它仍然给我CORS阻止错误?哪个错过了?我不认为班级工作正常,我如何追踪错误?

3 个答案:

答案 0 :(得分:2)

就像@Bill Bilal说的那样,我必须将它注册到我的web.xml,所以这是我如何在我的web.xml中注册它

<filter>
  <filter-name>cors</filter-name>
  <filter-class>com.myapp.springservice.utility.SimpleCORSFIlter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

答案 1 :(得分:0)

前段时间我有一个类似的CORS问题,使用类似的REST服务器。标头是在REST服务器的基类中设置的,但它似乎不起作用。我能够修复它的唯一方法是在我的.htaccess文件中添加以下行。

<ifModule mod_headers.c>
    Header always set Access-Control-Allow-Origin: "*"
    Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</ifModule> 

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

答案 2 :(得分:0)

您可以使用此过滤器来解决问题。它适用于Spring Restful

public class CORSFilter extends OncePerRequestFilter {

    private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {      
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
        } else { 
            chain.doFilter(req, res);
        }        
    }
}

我在帖子angularjs spring cross-origin request blocked

上找到了这个

希望得到这个帮助。