我正在嘗試使用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'中有問題。 –