【问题标题】:How to return html on get method in Spring app?如何在 Spring 应用程序中的 get 方法上返回 html?
【发布时间】:2018-02-17 18:43:37
【问题描述】:

我的问题可能很简单,我已经在使用 Spring mvc + jsp,但现在我不明白为什么控制器不返回 html 文件。现在我将 Spring Boot 与 Web 模块一起使用。

@Controller
@RequestMapping(value = "/test")
public class Main {
    private static final Logger logger = Logger
            .getLogger(Main.class.getName());

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        return "templates/hello.html";
    }

还有我的html文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>HelloWorld</title>
</head>
  <body>
  HELLO
  </body>
</html>

我总是出错:

白标错误页面 此应用程序没有显式映射 /error,因此您将其视为后备。 2018 年 2 月 17 日星期六 20:22:24 EET 出现意外错误(类型=未找到,状态=404)。 没有可用的消息

构建文件:

buildscript {
    ext {
        springBootVersion = '1.5.10.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'mikhailov.diplom.ae'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.9.RELEASE'

}

【问题讨论】:

  • 你如何称呼你的端点?

标签: spring-mvc spring-boot


【解决方案1】:

在您的构建文件中,您使用的是 thymeleaf:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    // https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.9.RELEASE'

} 

这种方法的“问题”是您必须显式定义 thymeleaf templateResolver bean 和 templateEngine。

另一方面,spring-boot 自带了一个开箱即用的解决方案,即

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

具有常规配置的所有内容。在这种情况下,您不需要定义您的 TempleteResolver 或您的 templateEngine(除非您真的不需要),您只需返回具有正确名称的字符串即可开始使用您的模板。

使用 spring 依赖,您只需从返回的字符串中删除“模板”前缀和 .html ext,它就会按预期工作:

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() {
    return "hello";
}

【讨论】:

  • 不,我不使用百里香叶(
  • 它是一个弹簧启动应用程序吗?你能发布你的 pom.xml 吗?
  • @senape 我认为如果缺少模板(最有可能是 500),他会得到与 404 不同的错误代码
  • @ОлегМихайлов compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.9.RELEASE' 说你正在使用百里香
猜你喜欢
  • 1970-01-01
  • 2021-02-17
  • 2018-03-01
  • 2017-12-30
  • 1970-01-01
  • 2016-03-30
  • 2018-03-08
  • 2022-12-21
  • 1970-01-01
相关资源
最近更新 更多