簡體   English   中英

為什么此REST服務無法正常工作?

[英]Why this REST service is not working?

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>

另一個類是應用程序包模型;

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

}

我真的不知道,連接正常。.我正在使用Glassfish 4服務器和MySQL數據庫...正在部署代碼,但是當我要訪問localhost:8080 / Task / ..(我的應用程序)時,它說的是:

“ HTTP狀態404-找不到/類型狀態報告

消息未找到描述請求的資源不可用。”

您提供的代碼正在工作(在注釋掉與持久性相關的內容時),我想您只是在混淆某些東西。

@ApplicationPath批注設置項目名稱后的根上下文。

如果您的項目名稱確實是Task ,則必須使用以下URL: http:// localhost:8080 / Task / rest / item

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

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM