我正在尝试使用@@ XmlRootElement批注将POJO映射到XML元素,但是在尝试访问端点时却不断收到javax.servlet.ServletException:java.lang.NullPointerException

Message.java

@XmlRootElement
public class Message {
    private long id;
    private String message;
    private Date created;
    private String author;

    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;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}


MessageService.java

public class MessageService {

    public List<Message> getAllMessages(){
        Message m1 = new Message(1L, "Hello World!", "Amine");
        Message m2 = new Message(2L, "Hi World!", "Amine");
        Message m3 = new Message(3L, "Hey World!", "Amine");
        List<Message> messages = new ArrayList<Message>();
        messages.add(m1);
        messages.add(m2);
        messages.add(m3);
        return messages;
    }
}


MessageResource.java

@Path("messages")
public class MessageResource {
    MessageService messageService = new MessageService();

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public List<Message> getMessages() {
        return messageService.getAllMessages();
    }

}


输出:
java - 如何修复JAX-RS中的javax.servlet.ServletException:java.lang.NullPointerException?-LMLPHP

最佳答案

好像泽西岛正在初始化问题
MessageService messageService =新的MessageService();

尝试使用其他方法创建此对象,您可以尝试自动装配该对象或将其移至getMessages()方法内的行上方。

但是我建议您以调试模式启动服务器,并确切地看到将要显示为null的内容。

07-24 09:35