【发布时间】:2015-12-11 19:10:15
【问题描述】:
我试图实现的是在另一个域中使用我的 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 请求失败)。
这是我通过这些链接生成的 JSON 值http://localhost:8080/SpringServiceJsonSample/service/updatepool/1
{"userid":1,"firstName":"brand","lastName":"bennet","email":"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;
}
}
然后我创建了基于 spring.io 的 SimpleCORSFilter 教程,所以这是我的 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 阻塞错误?我错过了什么?我不认为该类工作正常,我必须如何跟踪错误?
【问题讨论】:
-
您的自定义过滤器“SimpleCORSFIlter”需要在您的 web.xml 文件中注册。
-
@BillBilal 怎么注册?
标签: json web-services spring-mvc cors