Я следил за многочисленными примерами и обучающими программами, пытающимися запустить мой веб-сервис REST, но без каких-либо успехов. Я использую IntelliJ 13 Maven3, Java 7 и Tomcat 7.Tomcat 7 Джерси REST не работает
Мой pom.xml выглядит следующим образом:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jafwatt</groupId>
<artifactId>rest-service</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m10</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
Моя web.xml выглядит следующим образом:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>rest</display-name>
<servlet>
<servlet-name>restServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.jafwatt.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
CustomerResource .java
package com.jafwatt.rest;
import com.jafwatt.rest.entity.Customer;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@Path("/customers")
public class CustomerResource {
private Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>();
private AtomicInteger idCounter = new AtomicInteger();
@GET
@Path("/hello")
@Produces("text/plain")
public String getCustomers() {
return "Hello";
}
@POST
@Consumes("application/xml")
public Response createCustomer(InputStream is) {
Customer customer = readCustomer(is);
customer.setId(idCounter.incrementAndGet());
customerDB.put(customer.getId(), customer);
System.out.println("Created customer " + customer.getId());
return Response.created(URI.create("/customers/"
+ customer.getId())).build();
}
@GET
@Path("{id}")
@Produces("application/xml")
public StreamingOutput getCustomer(@PathParam("id") int id) {
final Customer customer = customerDB.get(id);
if (customer == null) {
throw new WebApplicationException(
Response.Status.NOT_FOUND);
}
return new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
private void outputCustomer(OutputStream outputStream, Customer customer) {
}
};
}
@PUT
@Path("{id}")
@Consumes("application/xml")
public void updateCustomer(@PathParam("id") int id,
InputStream is) {
Customer update = readCustomer(is);
Customer current = customerDB.get(id);
if (current == null)
throw new WebApplicationException(Response.Status.NOT_FOUND);
current.setFirstName(update.getFirstName());
current.setLastName(update.getLastName());
current.setStreet(update.getStreet());
current.setState(update.getState());
current.setZip(update.getZip());
current.setCountry(update.getCountry());
}
private Customer readCustomer(InputStream is) {
return new Customer();
}
}
Maven строит WAR без ошибок и Tomcat развертывает WAR без ошибок, но не сочетание URL-адреса получают не что иное, как ответ 404.
Корневой контекст «отдыха» и URL, я пытался:
http://localhost:8090/rest
http://localhost:8090/rest/custsomers
http://localhost:8090/rest/custsomers/hello
Я знаю, что Tomcat работает на этом порту, потому что я могу получить доступ к приложению менеджера.
Я читал столько сообщений в Stackoverflow и в других местах, и я очень расстроен тем, что то, что должно быть относительно простой задачей, вне меня.
Пожалуйста, помогите.
Что происходит, когда и вызвать API? это 404? – Bhaskara
Пожалуйста, добавьте точные сообщения об ошибках в свой вопрос; также включают URL-адрес образца запроса, чтобы мы могли видеть, как вы звоните в свою службу. – sherb
Я понял на диске домой, что пропустил эту мелочь. Отредактировано, чтобы объяснить, что я получаю 404s. – jafwatt