我有一个restful webservice,它返回一个用户列表。我正在使用AngularJS调用该方法 我的Restful Webservice:
package webservice;
import java.sql.Connection;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.Users;
@Path("/WebService")
public class UsersService {
@GET
@Path("/GetUsers")
@Produces("application/json")
public String user()
{
String users = null;
try
{
ArrayList<Users> usersList = null;
ProjectManager projectManager= new ProjectManager();
usersList = projectManager.GetUsers();
Gson gson = new Gson();
System.out.println(gson.toJson(usersList));
users = gson.toJson(usersList);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}
return users;
}
}
,输出为:
[{"userId":1,"userName":"sdsouza"},{"userId":3,"userName":"administrator"}]
http url让结果很好。
Angular Js中的我的controllers.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', ['$scope', '$http', function($scope, $http) {
$http.get(
'http://localhost:8081/TestDataRestful/REST/WebService/GetUsers'
).success(function(data) {
$scope.$apply(function () {
$scope.users = data;
});
})
.error(function(data) {
$scope.message="error";
});
}])
当我运行html页面时,我看到调用正在进行。控制台打印出结果但是html页面打印出错误消息并且没有用户的视线。我是一个菜鸟。我会如果有人能发现错误,我将感激不尽。我已经与它斗争了很长一段时间。谢谢你。
<ion-view view-title="Dashboard">
<ion-content class="padding">
<div class="list card">
<div class="item item-divider">Recent Updates</div>
<div class="item item-body">
{{message}}
</div>
<div class="item item-body" ng-repeat="user in users">
{{user}}
</div>
</div>
</ion-content>
</ion-view>
答案 0 :(得分:0)
这不是代码。我需要在webapp的web.xml文件中添加CORS过滤器。 如果您使用的是Tomcat 7及更高版本,则无需添加cors jar,只需在xml文件中包含过滤器即可。
http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-
Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-
Credentials</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
特别感谢Mike的文章。我使用了离子。所以我可以跳过在js文件中包含httpProvider的第一个配置。
http://mikesknowledgebase.azurewebsites.net/pages/Services/WebServices-Page8.5.htm