【发布时间】:2014-12-31 16:49:56
【问题描述】:
我关注了一些关于 Spring+Maven+RESTful 服务示例的博客/文章,并关注了这一篇 - http://www.concretepage.com/spring-4/spring-4-rest-web-service-json-example-tomcat
我按照示例中的步骤从头开始创建我的项目,但是我的安静服务没有返回响应。以下是我认为可能缺少某些内容的代码:
@RestController
@RequestMapping("/data")
public class PersonController {
@RequestMapping("/person")
public String getPersonDetail(@RequestParam(value = "id",required = false,
defaultValue = "0") Integer id) {
return "Hello " + id;
}
这里是 WebAppInitializer
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
我也试过换成spring代替spring boot,这是我当前的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.concretepage</groupId>
<artifactId>Spring4</artifactId>
<version>1</version>
<packaging>war</packaging>
<properties>
<spring.version>4.1.3.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
我了解到,如果我使用注解,我不需要在 web.xml 中指定额外的映射。这是我的 web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app 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"
version="2.4">
<display-name>JAX RS Application</display-name>
</web-app>
最后,我尝试使用 http://localhost:8080/Spring4/data/person?id=5 访问此服务
但它只是返回“未找到”。当我访问http://localhost:8080/Spring4/ 时,它返回“Forbidden”,因此该应用程序肯定会被部署。
我在这里错过了什么?
【问题讨论】:
-
你用的是什么服务器?
-
我尝试在 tomcat 8 和 wildfly 8 上进行部署。两者的结果相同。
-
基于注解的 servlet 配置在 2.4 中不可用。
-
@chrylis - 我尝试将其更改为 3.1,但 Eclipse 将其标记为红色。那么哪个版本有效?
-
我相信基于注释的 servlet 配置的最低版本是 3.0。
@RequestMapping(value="/person", method = RequestMethod.GET, produces = "text/plain")有帮助吗?