POJO的JAX-RS示例

时间:2014-01-29 22:08:27

标签: java rest maven jersey jax-rs

如果有人能给我一个小例子来说明我应该如何配置POJO类以使其在JAX-RS中用作资源

,我将不胜感激。

我有以下POJO

import javax.xml.bind.annotation.XmlRootElement;

/**
 * Created by ranjur on 1/27/14.
 */
@XmlRootElement
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 + "]";
    }

}

我的实现类是:

import org.apache.log4j.Logger;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;


@Path("/test")
public class test {

    private static Logger logger = Logger.getLogger(test.class);



    @GET
    @Produces(MediaType.TEXT_PLAIN)  // works perfectly
    public Response getMsg()
    {
    logger.info("Inside getMsg()");

    String output = "hello world";

    return Response.status(200).entity(output).build();

    }

  /*   @GET                                      // I get a HTTP 500 , server error 
     @Path("/get")
     @Produces(MediaType.APPLICATION_JSON)
     public Track getTrackInJSON() {

         Track track = new Track();
         track.setTitle("Enter Sandman");
         track.setSinger("Metallica");

         return track;
     }
    */


    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");

        //String test = " hello world";
        return Response.status(201).entity(track).build();

    }


    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
 //   @Produces(Me)

    public Response createTrackInJSON(Track track) {
        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();

    }

    @POST
    @Path("/getValue")
    @Produces(MediaType.APPLICATION_XML)
    public void createXML()
    {
        String result = " get the track";
        //        return result.createXML();
        // check this line

    }



        }

我仍然无法将@Consume@Produce与MIME类型(如json)一起使用。在我的映射中我做错了什么。举例来说明这一点非常有用。

我的依赖关系是:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.8</version>
</dependency>

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.8</version>
</dependency>

0 个答案:

没有答案