【发布时间】:2017-03-12 15:16:27
【问题描述】:
我正在尝试使用 this tutorial 之后的 Spring Boot 创建一个简单的 REST 服务。 webapp 文件夹(index.html)中的“Hello World”html 文件在http://localhost:8080/my-rest-app/ 上打开(我创建了一个 Maven-Web-App,因为我想为该服务创建一个“欢迎页面”)。但是,如果我尝试访问 http://localhost:8080/my-rest-app/user 上的 REST 服务,我会收到 404 消息。
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>service</groupId>
<artifactId>my-rest-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>my-rest-app</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.java:
package service.my.rest.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@ComponentScan({"service.my.rest.app", "service.my.rest.app.controller"})
//@ComponentScan(basePackageClasses = UserController.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
用户控制器.java:
package service.my.rest.app.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String getUser() {
return "Hello";
}
}
我错过了什么?服务的 URL 是否错误?我在某处读到 Spring Boot REST 服务的上下文路径始终为/,这意味着我必须通过http://localhost:8080/my-rest-app/ 访问该服务,但这不起作用(没有index.html)。用server.contextPath=/my-rest-app 和server.port=8080 更改application.properties 中的上下文路径也没有帮助。
【问题讨论】:
-
您使用战争包装而不只是罐子有什么特殊原因吗?
-
从
getUser()方法中删除@RequestMapping(method = RequestMethod.GET)。它会通过没有注释的 get 方法调用它 + 你没有在其中指定一个值。 -
@chrylis 我需要在 Tomcat 上运行 REST 服务以及普通网页。因此 html 文件和服务在同一个 war 包中。其实我没有选择。 Netbeans 在服务器上进行了打包和部署。
-
Spring Boot 将愉快地提供 HTML 和 JSON,如果需要,甚至可以来自完全相同的 URL。无需使用外部容器。
标签: java rest spring-boot