Остальные веб-сервисы не возвращают XML-ответ и даже не входят в консоль в Eclipse - PullRequest
0 голосов
/ 30 сентября 2018

Создание спокойного приложения, но оно не возвращает ответ в XML.Даже при попадании в URL-адрес на консоли не ведется журнал "http://localhost:8080/message/webapi/messages".

. Я возвращаю список и использую @Produces (MediaType.APPLICATION_XML) для возврата ответа в XML.

MessageResource.java

package org.porwal.restful.message.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.porwal.restful.message.model.Message;
import org.porwal.restful.message.service.MessageService;

@Path("/messages")
public class MessageResource {

    MessageService ms = new MessageService();

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public List<Message> getMessage(){
        return ms.getAllMessage();
    }

}

Message.java

package org.porwal.restful.message.model;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement( name = "Message" )
public class Message {

    public long id;
    public String message;
    public Date created;
    public String author;

    public Message() {

    }

    public Message(long id, String message, String author) {
        this.id = id;
        this.message = message;
        this.author = author;
        this.created = new Date();
    }

    public long getId() {
        return id;
    }
    @XmlElement (name = "ID")
    public void setId(long id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    @XmlElement (name = "Message")
    public void setMessage(String message) {
        this.message = message;
    }
    public Date getCreated() {
        return created;
    }
    @XmlElement (name = "Created")
    public void setCreated(Date created) {
        this.created = created;
    }
    public String getAuthor() {
        return author;
    }
    @XmlElement (name = "Author")
    public void setAuthor(String author) {
        this.author = author;
    }

}

Это работает, если я не использую аннотацию @XMLRootElement и возвращается TEXT_PLAINхорошо через URL. Я также пытался удалить @XmlElement для каждого поля, но не повезло. Когда я удаляю @XMLRootElement, то ошибка MessageBodyWriter может быть замечена в журналах на консоли затмения, но когда включает в себя @XMLRootElement, то нет журналов на консоли затмений и URL "http://localhost:8080/message/webapi/messages" выдает ошибку:

Ошибка в случае отсутствия @XmlRootElement.

org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo SEVERE: MessageBodyWriter not found for media type=application/xml, type=class java.util.ArrayList, genericType=java.util.List<org.porwal.restful.message.model.Message>. This exception comes only when i commented the line "//@XmlRootElement( name = "Message" )".

Состояние HTTP 500 - Внутренняя ошибка сервера

Может кто-нибудь сказать, что мне здесь не хватает?

1 Ответ

0 голосов
/ 01 октября 2018

Вам нужно сделать все свои поля в классе Message приватными.Если вы оставите их как общедоступные, то JAXB будет рассматривать его как свойство и будет считать его дублирующими свойствами, поскольку у вас также есть свойства JavaBean (getters / setters).

@XmlRootElement( name = "Message" )
public class Message {

    private long id;
    private String message;
    private Date created;
    private String author;

    // ...
}

Как я понял этоЭто было сделано с использованием универсального ExceptionMapper

@Provider
public class DebugExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception exception) {
        exception.printStackTrace();
        return Response.serverError().entity(exception.getMessage()).build();
    } 
}

. Вы можете зарегистрировать это в своем приложении, и оно будет перехватывать не отображенные исключения, и вы можете делать с ним все, что захотите.Здесь мы просто печатаем трассировку стека.Если мы не справимся с этим, его просто проглотят, и мы никогда не узнаем, что произошло.

При запуске приложения с ExceptionMapper, вот сообщение об ошибке, которое я получил.

Caused by: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 4 counts of IllegalAnnotationExceptions
Class has two properties of the same name "author"
    this problem is related to the following location:
        at public java.lang.String com.example.Message.getAuthor()
        at com.example.Message
    this problem is related to the following location:
        at public java.lang.String com.example.Message.author
        at com.example.Message
Class has two properties of the same name "created"
    this problem is related to the following location:
        at public java.util.Date com.example.Message.getCreated()
        at com.example.Message
    this problem is related to the following location:
        at public java.util.Date com.example.Message.created
        at com.example.Message
Class has two properties of the same name "id"
    this problem is related to the following location:
        at public long com.example.Message.getId()
        at com.example.Message
    this problem is related to the following location:
        at public long com.example.Message.id
        at com.example.Message
Class has two properties of the same name "message"
    this problem is related to the following location:
        at public java.lang.String com.example.Message.getMessage()
        at com.example.Message
    this problem is related to the following location:
        at public java.lang.String com.example.Message.message
        at com.example.Message

Вы можете ясно видеть, в чем проблема.И кроме того, чтобы избежать этой ошибки, именно так должна работать инкапсуляция;поля должны быть закрытыми и доступны через геттеры и сеттеры.

...