2015-04-11 3 views
0
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Почему эта служба REST не работает?

<?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 ... код развертывания, но когда я хочу, чтобы получить доступ к локальному хосту: 8080/задач /. . (мое приложение) единственное, что он говорит это:

"HTTP Status 404 - отчет о состоянии не найден/Тип

messageNot Найдено DescriptionThe запрошенный ресурс не доступен."

+0

Какие URL вы пытаетесь получить доступ? – unwichtich

+0

Я попытался протестировать службу с почтальоном: я получаю его с localhost: 8080/Task/rest –

+0

Но URL явно должен содержать 'item', потому что вы указали это в своем' @ Path'. – unwichtich

ответ

1

Код, который вы указали, работает (при комментировании материала, связанного с сохранением), я думаю, вы просто что-то путаете.

Аннотации @ApplicationPath задает корень контекста, который появляется после имени вашего проекта.

Если проецировать имя действительно Task вы должны использовать этот URL: http://localhost:8080/Task/rest/item

В противном случае: http://localhost:8080/YOUR_PROJECT_NAME/rest/item

Смотрите также:

Смежные вопросы