我尝试构建一个RESTfull Web服务。
在前端,我使用jQuery来获取数据。
在后端我正在尝试使用www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson /
中的示例从浏览器调用127.0.0.1:8080/restEx/rest/json/get我得到了预期的答案:
{"title":"Enter Sandman","singer":"Metallica"}
但是当我尝试使用$ .get()获取这些数据时,我得不到答案。 看着Firebug告诉我,我没有得到数据。
我也尝试了
return Response.ok("{status: 'success'}").header("Access-Control-Allow-Origin", "*").build();
正如我在另一个问题中找到的解决方案 现在我在Firebug中看到了数据,但jQuery仍然没有执行成功函数。我仍然只看到失败功能。
那么我做错了什么?我怎样才能使这些东西工作?
我正在使用jQuery 2.0.2,Jersey 1.8(我在jersey.java.net/documentation/latest/getting-started.html#running-project中使用泽西2尝试了相同的结果)并且项目部署在Tomcat 7。
的index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="assets/js/jquery-2.0.2.js"></script>
</head>
<body>
<div id="first" class="container"></div>
<script type="text/javascript">
var url = "http://127.0.0.1:8080/restEx/rest/json/get";
$.get(url, {}, function(){alert("success");},"json")
.fail(function(){alert("fail");})
;
</script>
</body>
</html>
的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mkyong.common</groupId>
<artifactId>RESTfulExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>RESTfulExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
</dependencies>
<build>
<finalName>restEx</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
的web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</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>com.mkyong.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
JSONService.java
package com.mkyong.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.mkyong.Track;
@Path("/json")
public class JSONService {
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
@GET @Path("/test") @Produces(MediaType.APPLICATION_JSON)
public JSONObject test() throws JSONException{
return new JSONObject("{status:'success'}");
}
}
Track.java
package com.mkyong;
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
@Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
答案 0 :(得分:0)
错误的网址,将http://127.0.0.1:8080/restEx/rest/json/test
更改为http://127.0.0.1:8080/restEx/rest/json/get
:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="assets/js/jquery-2.0.2.js"></script>
</head>
<body>
<div id="first" class="container"></div>
<script type="text/javascript">
var url = "http://127.0.0.1:8080/restEx/rest/json/get";
$.get(url, {}, function(){alert("success");},"json")
.fail(function(){alert("fail");})
;
</script>
</body>
</html>
答案 1 :(得分:0)
感谢Marcos Zolnoswski的链接,我能够解决我的问题。 通过那里提供的信息,我能够找到http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/,其中描述了如何将丢失的标头添加到所有请求的解决方案。
作为我的Jersey Servlet的init-Parameter:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>your.package.ResponseCorsFilter</param-value>
</init-param>
ResponseCorsFilter.java
package yoiur.package.security;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
public class ResponseCorsFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {
ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
String reqHead = req.getHeaderValue("Access-Control-Request-Headers");
if(null != reqHead && !reqHead.equals("")){
resp.header("Access-Control-Allow-Headers", reqHead);
}
contResp.setResponse(resp.build());
return contResp;
}
}