线程中的@POST异常" main" javax.ws.rs.NotAllowedException:不允许HTTP 405方法

时间:2017-03-06 11:40:20

标签: java xml hibernate post jax-rs

我是JAVA的新手,我正在尝试提供服务:我想用JAX-RS和Hibernate(JPA)进行测试,这里的任务是将JAX-RS的信息发送到另一个类来保持一个对象Utilisateur和我在目前和很长一段时间之前得到了关于在我的数据库中使用JPA插入新对象的相同错误。当我在我的MAIN课程中进行测试时,我总是得到这个错误: 线程" main"中的例外情况javax.ws.rs.NotAllowedException:HTTP 405方法不允许

这是我的类(我的MAIN,我的服务类,它使对象的持久化,我的Utilisateur类,它是将要持久化的Object类,我的web.xml和我的persistence.xml)。我还要在控制台中发布错误代码:

我的主要课程(测试):

    package clientREST;

import java.io.IOException;
import java.net.UnknownHostException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import modele.Utilisateur;

public class ClientMain {


    public static void main(String[] args) throws UnknownHostException, IOException, Exception {

        /* String nom = null ;
         String prenom = null;
         String pseudo = null;          
         String email = null;
         String password = null;
         String message = null;*/

         String nom  = "Vidal";
         String prenom = "Fabrice";
         String pseudo = "Doppio";
         String email = "fabricevidal@test.fr";
         String password = "vfd";
         String message;

        Client client = ClientBuilder.newClient();      
        WebTarget cible = client.target(UriBuilder.fromPath("http://172.17.0.5:8080/creationprofiltestmain/"));
        WebTarget ciblefinale = cible.path("service");
        System.out.println("ok");

        Utilisateur util = ciblefinale.queryParam("nom", nom)
                                    .queryParam("prenom", prenom)
                                    .queryParam("pseudo",pseudo)
                                    .queryParam("email", email)
                                    .queryParam("password", password)

                    .request(MediaType.APPLICATION_XML).get(Utilisateur.class); 

            System.out.println("ok 2");
            message = "Vous venez de créez votre profil Monsieur " +util.getNom()+ ".";
            System.out.println(message + util.getNom()
                                        +util.getPrenom()
                                        +util.getPseudo()
                                        +util.getEmail()
                                        +util.getPassword());





    }

}

我的服务类:

package composants;


import javax.persistence.EntityManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import modele.Utilisateur;
import ressources.FournisseurDePersistance;

@Path("service")
public class ServiceCreationProfil {

    private String nom;
    private String prenom;
    private String pseudo;
    private String email;
    private String password;
    private String message;



    EntityManager em = null;

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.TEXT_PLAIN)
    //@Path("/getutil")
    public Utilisateur getUtil (@QueryParam("nom") String nom,
                                @QueryParam("prenom") String prenom,
                                @QueryParam("pseudo") String pseudo,
                                @QueryParam("email") String email, 
                                @QueryParam("password") String password){


        Utilisateur util = new Utilisateur (nom, prenom, pseudo, email, password);

        try {

        em = FournisseurDePersistance.getInstance().fournir();
        em.getTransaction().begin();
        em.persist(util);
        em.getTransaction().commit();
        em.close();

        }
        catch (Exception e) {
            em.getTransaction().rollback();
            e.printStackTrace();
            System.out.println(e);
            message = "voila l'erreur :"+e;
        }
    // mettre un catch avec un try plus tard


        return util;
    }

    //************************************** GETTERS ET SETTERS ET CONTRUSCTEUR ******************************************************


    public ServiceCreationProfil() {
        super();
    }


    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getEmail() {
        return email;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPseudo() {
        return pseudo;
    }

    public void setPseudo(String pseudo) {
        this.pseudo = pseudo;
    }

}

我的Utilisateur课程(即将持续的课程):

package modele;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@Entity
@Table(name = "UTILISATEUR")
public class Utilisateur {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id_user;
    @Column(nullable = false)
    private String nom;
    @Column(nullable = false)
    private String prenom;
    @Column(nullable = false, unique = true)
    private String pseudo;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = false)
    private String password;
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Annonce> annonces = new ArrayList<>();

    public Utilisateur() {
        super();
    }
    //***************************************** TEST ***********************************************


    //***************************************** TEST ***********************************************

    public Utilisateur(String nom, String prenom, String pseudo, String email, String password) {
        super();
        this.nom = nom;
        this.prenom = prenom;
        this.pseudo = pseudo;
        this.email = email;
        this.password = password;
    }

    public List<Annonce> getAnnonces() {
        return annonces;
    }

    public void setAnnonces(List<Annonce> annonces) {
        this.annonces = annonces;
    }

    public String getEmail() {
        return email;
    }

    public int getId_user() {
        return id_user;
    }

    public void setId_user(int id_user) {
        this.id_user = id_user;
    }

    public String getPseudo() {
        return pseudo;
    }

    public void setPseudo(String pseudo) {
        this.pseudo = pseudo;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

}

我的persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
             <persistence-unit name="peuplement" transaction-type="RESOURCE_LOCAL">

        <class>modele.Utilisateur</class>  
        <class>modele.Annonce</class>  
        <class>modele.Type_annonce</class>

      <properties>
         <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
         <property name="javax.persistence.jdbc.user" value="derby"/>
         <property name="javax.persistence.jdbc.password" value="derby"/>
         <property name="javax.persistence.jdbc.url" value="jdbc:derby://172.17.0.2:1530/ppeDB;update=true"/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSixDialect"/>
         <property name="hibernate.max_fetch_depth" value="3"/>     
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit>
</persistence>

我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Service REST creation profil</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>composants</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

<persistence-context-ref>
    <persistence-context-ref-name>peuplement</persistence-context-ref-name>
    <persistence-unit-name>peuplement</persistence-unit-name>
    <persistence-context-type>Transaction</persistence-context-type>
  </persistence-context-ref>
</web-app>

错误代码:

ok
Exception in thread "main" javax.ws.rs.NotAllowedException: HTTP 405 Method Not Allowed
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1023)
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:819)
    at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:701)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:697)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at clientREST.ClientMain.main(ClientMain.java:43)

我是那个论坛的新手,对不起如果我错过了很多东西,真的很抱歉。 在那次测试之后,我将创建一个GUI来连接SERVICE和GUI与JSF(xhtml)。 你可以看到我不是英国人,对那些错误感到抱歉。

1 个答案:

答案 0 :(得分:2)

此错误表示您正在尝试向服务器端不允许/存在的方法发出请求

在您的情况下 GET ,您正在尝试发出 GET 请求,但您没有在服务中声明

您的客户代码:

....request(MediaType.APPLICATION_XML).get(Utilisateur.class); 

和您的服务代码:

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
//@Path("/getutil")
public Utilisateur getUtil....

更改您的服务代码,改为使用@GET。

对于记录:您正在使用REST动词,因为POST应该用于ADD,因此您可能希望更改客户端代码以进行POST,而不是GET。但是你必须改变@QueryParam。这不是在POST中传递params的方式

您可能需要检查此answer,以便在请求中传递POST表单字段。