提问者:小点点

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


我试图使用@@XmlRootElement注释将POJO映射到XML元素,但在试图访问我的endpoint时,我一直得到一个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();
    }

}


共1个答案

匿名用户

似乎Jersey在初始化MessageService MessageService=new MessageService()时出现了问题;

尝试一些不同的方法来创建这个对象,您可以尝试自动生成它或者移动到getMessages()方法的上面一行。

但是我会建议您在调试模式下启动服务器,并确切地看到什么是空的。