为什么这个REST服务不起作用?

时间:2015-04-11 19:13:37

标签: java mysql glassfish jersey

package model;

import java.net.URI;
import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/item")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Stateless
public class InfoRestService {
    // the PersistenceContext annotation is a shortcut that hides the fact
    // that, an entity manager is always obtained from an EntityManagerFactory.
    // The peristitence.xml file defines persistence units which is supplied by
    // name
    // to the EntityManagerFactory, thus dictating settings and classes used by
    // the
    // entity manager
    @PersistenceContext(unitName = "Task")
    private EntityManager em;

    // Inject UriInfo to build the uri used in the POST response
    @Context
    private UriInfo uriInfo;

    @POST
    public Response createItem(PersonInfo item) {
        if (item == null) {
            throw new BadRequestException();
        }
        em.persist(item);

        // Build a uri with the Item id appended to the absolute path
        // This is so the client gets the Item id and also has the path to the
        // resource created
        URI itemUri = uriInfo.getAbsolutePathBuilder().path(item.getId()).build();

        // The created response will not have a body. The itemUri will be in the
        // Header
        return Response.created(itemUri).build();
    }

    @GET
    @Path("{id}")
    public Response getItem(@PathParam("id") String id) {
        PersonInfo item = em.find(PersonInfo.class, id);

        if (item == null) {
            throw new NotFoundException();
        }

        return Response.ok(item).build();
    }

    // Response.ok() does not accept collections
    // But we return a collection and JAX-RS will generate header 200 OK and
    // will handle converting the collection to xml or json as the body
    @GET
    public Collection<PersonInfo> getItems() {
        TypedQuery<PersonInfo> query = em.createNamedQuery("PersonInfo.findAll",
                PersonInfo.class);
        return query.getResultList();
    }

    @PUT
    @Path("{id}")
    public Response updateItem(PersonInfo item, @PathParam("id") String id) {
        if (id == null) {
            throw new BadRequestException();
        }

        // Ideally we should check the id is a valid UUID. Not implementing for
        // now
        item.setId(id);
        em.merge(item);

        return Response.ok().build();
    }

    @DELETE
    @Path("{id}")
    public Response deleteItem(@PathParam("id") String id) {
        PersonInfo item = em.find(PersonInfo.class, id);
        if (item == null) {
            throw new NotFoundException();
        }
        em.remove(item);
        return Response.noContent().build();
    }

}


package model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;


/**
 * The persistent class for the person_info database table.
 * 
 */
@Entity
@XmlRootElement
@Table(name="person_info")
@NamedQuery(name="PersonInfo.findAll", query="SELECT p FROM PersonInfo p")
public class PersonInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private String id;

    private String email;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    public PersonInfo() {
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}
  

的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="Task">
        <jta-data-source>jdbc/DBtest</jta-data-source>
        <class>model.PersonInfo</class>
    </persistence-unit>
</persistence>

,另一个类是Application 包模型;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rest")
public class ApplicationConfig extends Application{

}

我真的不知道,连接正常。我使用Glassfish 4服务器和MySQL数据库...代码正在部署但是当我想访问localhost时:8080 / Task / ..(我的应用程序)它唯一说的是:

  

&#34; HTTP状态404 - 未找到/类型状态报告

     

messageNot Found   description请求的资源不可用。&#34;

1 个答案:

答案 0 :(得分:1)

你提供的代码正在工作(在评论持久性相关的东西时),我猜你只是在混淆什么。

@ApplicationPath注释设置项目名称后面的根上下文。

如果项目名称确实是任务,则必须使用以下网址:http://localhost:8080/Task/rest/item

否则:http://localhost:8080/YOUR_PROJECT_NAME/rest/item

另见: