RESTful Web 服务使用 jQuery ajax

RESTful web services using jQuery ajax

我正在使用 restful Web 服务使用 java

@Path("/data")
public class StudentDataService {

    StudentInfo st=new StudentInfo();

    @GET
    @Path("/mydata")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public List<Student> findAll() {
        System.out.println("data returned to the web service");
        return st.populateData();
    }
}

我正在返回包含学生姓名、ID、分数等的数据列表

尝试使用 jQuery ajax 调用此方法,如下所示:

function findAll() {
console.log('findAll');
 $.ajax({  
       type: "GET",  
       url: "http://localhost:9297/StudentData/rest/data/mydata",  
       dataType: "json",  
       crossDomain: true,
       success: function(resp){  
         // we have the response  
         alert("Data\n '" + resp + "'");  
       },  
       error: function(e){  
         alert('Error: ' + e);  
       }  
     });
}

我遇到错误

它也在控制台上给出错误,如 "no elements found"

使用 javax.ws.rs.core.Response 对象并构建输出。否则有你自己的包装器 class 并包装你的输出和 return 包装器 class 返回响应。

我建议您在服务器端使用 gson 来处理 json,因为它非常易于使用。例如:

List<Student> items = new ArrayList<>();
while (...) {
  items.add(new Student(...));
}
Gson gson = new Gson();
return gson.toJson(items);

这只是一个示例,请根据您的要求采用。

"getting exception: javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class java.util.ArrayList, and Java type java.util.List<dao.Student>, and MIME media type application/json was not found""

您似乎缺少 JSON 提供商。如果你使用 Maven,你可以添加这个依赖

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.4.0</version>
</dependency>

如果您不使用 Maven,请查找这些 jar

您可以搜索并下载所有的jarhere

然后您可以注册提供商,方法是将 Jackson 包添加到要扫描的包中(在您的 web.xml 配置中)

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>
            your.packages.to.scan,
            com.fasterxml.jackson.jaxrs.json
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

您可能 运行 遇到 问题。由于您正在尝试从服务器获取类型 application/json 并且您的请求是跨域的。如果像@user1129947 建议的那样用 Response object 包装 jax-rs 方法,您可以修改响应的 headers 以允许 cross-origin 请求,如下所示:

import javax.ws.rs.core.Response;

@Path("/data")
public class StudentDataService {

    StudentInfo st=new StudentInfo();

    @GET
    @Path("/mydata")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response findAll() {
        return Response.ok(st.populateData())
            .header("Access-Control-Allow-Origin", "*")
            .build();
    }
}

header Access-Control-Allow-Origin: * 现在将在响应中,告诉浏览器它被允许接收 application/json 数据。

请注意 header 中的 * 参数允许任何域访问此资源

如果您想确保只有您的域可以访问此资源,那么您必须将 header 的值设置为特定域。

如果您使用自定义 headers 或者您最终想要将 cookie 发送到服务器,那么您将不得不处理超出此答案范围的预检请求。

See Mozilla's documentation on CORS for more information

奖金编辑:

对于将 CDI 与 JAX-RS 一起使用的任何人,您可以查看 this filter-interceptor combo 以处理 CORS