我正在尝试使用Java配置创建Spring 4 RESTFul服务并将其部署到Tomcat。但我无法击中端点。我错过了什么?这是我的。如何使用Java配置创建Spring RESTFul服务?
我有一个有setter和getters的Greeting POJO。
public class Greeting {
private BigInteger id;
private String text;
//setters and getters
}
我有一个问候控制器。
@Controller
public class GreetingController {
private static BigInteger nextId;
private static Map<BigInteger, Greeting> greetingMap;
//have some code to store Greetings in greetingMap
@RequestMapping(value = "/api/greetings", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Greeting>> getGreetings() {
Collection<Greeting> greetings = greetingMap.values();
return new ResponseEntity<Collection<Greeting>>(greetings, HttpStatus.OK);
}
}
我有一个配置类。
@Configuration
@ComponentScan(basePackages = "org.example")
public class GreetingConfiguration {
}
,这是我的src /主/ web应用/ WEB-INF/web.xml中
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.example.ws.configuration.GreetingConfiguration</param-value>
</init-param>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.example.ws.configuration.GreetingConfiguration</param-value>
</context-param>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
我部署到Tomcat。 Tomcat开始正常。我试图打它http://localhost:8080/api/greetings,它给了我404。我错过了什么?
谢谢!
尝试用替换'@ Controller' '@ RestController'你能够访问应用程序中的欢迎页面吗?没有根上下文?并使用'/ *'作为url-pattern。 – Isukthar
我认为你在'GreetingConfiguration'中有问题。 –