Question

I try to build a RESTfull Webservice.

On the frontend I use jQuery to get the data.

On the backend I am trying it with the example from www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Calling 127.0.0.1:8080/restEx/rest/json/get from the browser I get the answer as expected:

{"title":"Enter Sandman","singer":"Metallica"}

But when I try to get these data with $.get(), I get no answer. Looking in Firebug tells me, that I don't get data.

I also tried it with

return Response.ok("{status: 'success'}").header("Access-Control-Allow-Origin", "*").build();

as I found as a solution in another question In Firebug now I see the data, but still jQuery doesn't executes the success function. I still only see the fail-function.

So what I am doing wrong? How can I make this stuff working?

I am using jQuery 2.0.2, Jersey 1.8 (I tried it with Jersey 2 from jersey.java.net/documentation/latest/getting-started.html#running-project with same result) and the project is deployed on 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 + "]";
    }

}
Was it helpful?

Solution 2

Thanks to the link from Marcos Zolnoswski I was able to solve my Problem. With the inforamtion provided there, I was able to find http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/ where a solution is described how to add the missing header to all requests.

As init-Parameter to my Jersey Servlet:

<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;
    }

}

OTHER TIPS

Wrong URL, change http://127.0.0.1:8080/restEx/rest/json/test to 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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top