【发布时间】:2017-08-16 20:04:21
【问题描述】:
我正在尝试构建 Restful Web 服务。我的 Maven 项目名称是 rest,我正在关注 Spring's Building a RESTful Web Service 这样做,但我不想使用 Spring Boot,而只是创建一个战争并将其托管在 Tomcat 上在我的 ecrise/STS 中。这是我的 web.xml 和 XX-servlet.xml 文件:
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.rest" />
<mvc:annotation-driven/>
</beans>
GreetingController.java
@RestController
public class GreetingController2 {
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format("Hello %s", name));
}
}
当我在 Tomcat 上运行它时,URL:http://localhost:8080/rest 给出 404,我在 Tomcat 控制台 Aug 16, 2017 3:59:28 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/rest/] in DispatcherServlet with name 'rest'
中看到此消息,而我确实有映射。
当我点击 http://localhost:8080/rest/greeting 时,我会收到带有消息 The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers. 的 http 406,而根据教程,它应该转换为可以在浏览器中呈现的 JSON。
我花了很多时间试图找出并查看 SO 上的各种帖子以找出问题所在,但找不到。
【问题讨论】:
-
Akshay Srivastava 的回答帮助我找到了问题所在。除了他提到的之外,我没有 Jackson JSON 依赖项,这就是它无法将我的对象转换为 JSON 的原因。当我将这些添加到我的 pom.xml 中时,我可以看到 localhost:8080/rest/greeting 工作。
标签: spring rest spring-mvc spring-rest