Я пытаюсь воссоздать самый превосходный учебник vogella для создания REST с помощью java, JAX-RS и Jersey.
Я использую eclipse Kepler с перспективой Java-EE, tomcat 7.0.
Я создал класс Todo, класс TodoResource с соответствующими аннотациями и развернул его на tomcat 7. Я импортировал библиотеки jaxrs-ri в папку WEB-INF/lib в соответствии с инструкциями.
Класс Todo:
package com.vogella.jersey.jaxb.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Todo {
private String summary;
private String description;
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
TodoResource с аннотациями:
package com.vogella.jersey.jaxb.model;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
// This can be used to test the integration with the browser
@GET
@Produces({ MediaType.TEXT_XML })
public Todo getHTML() {
Todo todo = new Todo();
todo.setSummary("This is my first Todo");
todo.setDescription("This is my first Todo");
return todo;
}
}
веб.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>com.vogella.jersey.first</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>com.vogella.jersey.jaxb</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Я также создал клиента в соответствии с инструкциями.
Тест.java:
package com.vogella.jersey.first.client;
import java.net.URI;
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.Response;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.message.internal.MediaTypes;
public class Test {
public static void main(String[] args) {
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(getBaseURI());
System.out.println(target.path("rest").path("todo").request()
.accept(MediaType.APPLICATION_XML ).get(Response.class)
.toString());
System.out.println(target.path("rest").path("todo").request()
.accept(MediaType.APPLICATION_JSON ).get(Response.class)
.toString());
}
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/com.vogella.jersey.jaxb").build();
}
}
Для MediaType.APPLICATION_XML все работает отлично - сервер возвращает:
InboundJaxrsResponse{ClientResponse{method=GET, uri=http://localhost:8080/com.vogella.jersey.jaxb/rest/todo, status=200, reason=OK}}
Однако для MediaType APPLICATION_JSON, который мне действительно нужен, я получаю сообщение об ошибке:
InboundJaxrsResponse{ClientResponse{method=GET, uri=http://localhost:8080/com.vogella.jersey.jaxb/rest/todo, status=500, reason=Internal Server Error}}
Tomcat четко показывает мне проблему - мне кажется, он не умеет возвращать ответ JSON -
Nov 02, 2014 11:59:19 AM org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor aroundWriteTo
SEVERE: MessageBodyWriter not found for media type=application/json, type=class com.vogella.jersey.jaxb.model.Todo, genericType=class com.vogella.jersey.jaxb.model.Todo.
Насколько я понимаю, пакет jaxrs-ri 2.13 включает в себя все необходимое, включая зависимости, позволяющие мне это сделать, и что мне не нужно добавлять какой-либо поставщик JSON. Я все равно сделал это, например, я попытался добавить gson, я загрузил moxy jar и попытался добавить их в свою папку WEB-INF/lib и развернуть - все безрезультатно. Я не знаю, то ли я совсем запутался, то ли упускаю что-то простое?