我做了一个Rest Web服务:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/todo")
public class TodoResource {
@GET
@Produces({MediaType.APPLICATION_JSON})
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
@GET
@Produces({ MediaType.TEXT_XML })
public Todo getHTML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}
当我去网络浏览器&在地址栏中输入:
http://localhost:8080/LondonAirQuality.Rest/rest/todo/
它给了我:
{"description":"This is my first todo","summary":"This is my first todo"}
但是当我在JQuery方法中使用ajax调用来调用它时。 e.g。
$.ajax({
type: "GET",
url: "http://localhost:8080/LondonAirQuality.Rest/rest/todo/",
dataType: "json",
success: function(data) {
alert('OK : ' + data);
},
error: function (e) {
alert('KO: '+ e.text);
console.log(e);
alert("Status is: " + e.statusText);
}
});
我在这次调用中遇到错误,但是在Firebug中,我看到请求是200 OK,在响应中是正确的json。 有人可以帮帮我吗?
答案 0 :(得分:0)
问题是“同源策略”,解决方案是将ResponseCorsFilter类添加到服务器:
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;
}
}
并向Jersey Servlet添加一个init-param:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>de.vogella.jersey.jaxb.security.ResponseCorsFilter</param-value>
</init-param>
感谢。我希望这可以帮助别人。