我正在尝试构建Restful Web服务。我的Maven项目名称是 rest ,我正在关注Spring's Building a RESTful Web Service这样做但我不想使用Spring Boot但只是创建一个战争并托管它我的eclise / STS中的Tomcat。这是我的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>
其余-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上的各种帖子,以找出错误但却无法找到错误的帖子。
答案 0 :(得分:3)
你没有像
这样的默认映射
@RequestMapping( “/”)
根据您上面的代码,您应该在ur url下工作正常
http://localhost:8080/rest/greeting