Empty answer when trying to get JSON from Jersey Server
Empty answer when trying to get JSON from Jersey Server
try to build a RESTfull webservice.
On the backend I use a Jersey Server. On the Frontend I want to get the data with jQuery using ajax methods.
I took the example from http:-//www.mkyong.-com/webservices/jax-rs/json-example-with-jersey-jackson/ and tried to get the Data with $.getJSON and $.GET.
The problem is, that I always can't access the response data. Also jQuery always only executes the fail method.
After that I tried it with a simple servlet. With that I get the same result.
Does somebody know what I am doing wrong or how I can make this stuff working?
The project is deployed on a Tomcat 7.
<!DOCTYPE html>
<html>
<head>
<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/RESTfulExample/rest/json/metallica/get";
$.get(url, function(data){
alert("success");
$("#first").empty().append(JSON.stringify(data))
})
.fail(function(){alert("fail");})
;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<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/RESTfulExample/rest/json/metallica/get";
$.get(url, function(data){
alert("success");
$("#first").empty().append(JSON.stringify(data))
})
.fail(function(){alert("fail");})
;
</script>
</body>
</html>
Servlet:
JSONServlet.java
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
package de.liebich.test.servlet.json;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONArray;
public class JSONServlet extends HttpServlet {
private static final long serialVersionUID = -462470710392739675L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONArray arrayObj = new JSONArray();
arrayObj.put("MCA");
arrayObj.put("Amit Kumar");
arrayObj.put("19-12-1986");
arrayObj.put(24);
arrayObj.put("Scored");
arrayObj.put(new Double(66.67));
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println(arrayObj);
out.close();
}
}
package de.liebich.test.servlet.json;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONArray;
public class JSONServlet extends HttpServlet {
private static final long serialVersionUID = -462470710392739675L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JSONArray arrayObj = new JSONArray();
arrayObj.put("MCA");
arrayObj.put("Amit Kumar");
arrayObj.put("19-12-1986");
arrayObj.put(24);
arrayObj.put("Scored");
arrayObj.put(new Double(66.67));
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.println(arrayObj);
out.close();
}
}
web.xml
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Test</display-name>
<servlet>
<servlet-name>JSONServlet</servlet-name>
<servlet-class>de.liebich.test.servlet.json.JSONServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONServlet</servlet-name>
<url-pattern>/JSONServlet</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Test</display-name>
<servlet>
<servlet-name>JSONServlet</servlet-name>
<servlet-class>de.liebich.test.servlet.json.JSONServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONServlet</servlet-name>
<url-pattern>/JSONServlet</url-pattern>
</servlet-mapping>
</web-app>
Jersey
Track.java
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
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 + "]";
}
}
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 + "]";
}
}
JSONService
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
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 com.mkyong.Track;
@Path("/json/metallica")
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();
}
}
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 com.mkyong.Track;
@Path("/json/metallica")
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();
}
}
web.xml
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
<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>
I recently had to consume a REST API with a cross-domain call and i¡¯ve found a solution in this excellent blog post from Kdecherf.
The problem with this implementation is that you need to call a method for each of your api¡¯s methods.
So with the ContainerResponseFilter interface, you could do this for ALL of your methods ¡ transparently.
1 ¨C Configure web.xml
You just have to add an init-param to your Jersey Servlet
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.ezakus.api.web.security.ResponseCorsFilter</param-value>
</init-param>
2 ¨C ResponseCorsFilter
package com.ezakus.api.web.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;
}
}
And that¡¯s all !