我正在尝试构建Restful Web服务。我的Maven项目名称是其他我正在关注Spring's Building a RESTful Web Service这样做,但我不想使用Spring Boot,只是创建一个war并将其托管在我的eclise/STS的Tomcat中。这里是我的web.xml和XX-servlet.xml的文件:在运行Spring Restful web服务时没有Spring Boot的问题
的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>
休息-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时,我得到http 406,消息The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
,而根据教程,它应该转换为JSON,它可以在浏览器中呈现。
我花了很多时间试图弄清楚,看着SO上的各种帖子,以找出什么是错的,但不能。
阿克沙伊塔瓦的回答帮我找到这个问题。除了他提到的之外,我没有Jackson JSON依赖性,这就是为什么它无法将我的对象转换为JSON。当我将它们添加到我的pom.xml中时,我可以看到http:// localhost:8080/rest/greeting正在工作。 – Learner