【发布时间】:2017-07-14 21:22:49
【问题描述】:
我在 Spring Boot 中遇到了一些控制器问题。它应该返回一个index.html 文件,但它所做的是返回字符串“index”。
这里有你想找的东西,
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.earworm</groupId>
<artifactId>earworm</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
名为 LoginController.java 的控制器
package com.earwormproject.earwormcontrollers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LoginController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
@ResponseBody
public String createLoginForm(){
return "index";
}
@RequestMapping(value = "/profile", method = RequestMethod.GET)
@ResponseBody
public String addDataToLoginForm() {
return "profile";
}
}
这里是主类,
package com.earwormproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Earworm {
public static void main(String[] args){
SpringApplication.run(Earworm.class, args);
}
}
文件结构,
Earworm 是主类。到目前为止,我知道控制器检查 src/main/resources/templates 中的 html 模板,我已将 index.html 放入模板中,但不起作用。
当我要去http://localhost:8080/index 时,它会显示字符串index 而不是index.html 页面。像这样,
我已经在 SO 中解决了几乎所有类似的问题,尝试了所有这些但在这种情况下不起作用。一些线索会有很大帮助。谢谢你。
【问题讨论】:
-
您的视图解析器配置是什么?
-
"@ResponseBody public String createLoginForm(){ return "index"; }" 除了那个,它不能返回任何东西
-
你的 index.html 中有什么?也许一个词:“索引”? :-)
-
另外,为什么您的资源文件夹中没有 application.properties 文件?你删除了吗?它是有效的 Spring Boot 应用程序吗?你是如何创建它的?
标签: java spring maven spring-mvc spring-boot