vscode + springboot + HTML 搭建服务端(二)
2. 添加一个简单的展示
2.1 效果
2.2 代码
2.3 代码分解
-
1: @RestController 2: @RequestMapping(“/”) url访问路径:localhost:8080/,浏览器中输入此url会调用其作用的函数hello() 3: hello函数 返回一个字符串,显示在浏览器中
3. 添加并展示HTML文件
上面只是在url中展示了一个字符串,而实际项目中是需要将一个网页展示出来,所以下面我们来添加一个HTML文件。
3.1 添加 html 文件
-
在 src/main/resources/templates 路径下面添加 index.html 文件 index.html 文件代码: <!DOCTYPE html> <html> <head> <title>hello1111</title> </head> <body> <h1>index22222</h1> </body> </html>
3.2 添加 url 访问路径
-
url 访问路径添加为: localhost:8080/index
3.3 运行程序,查看结果
3.3.1 很不幸的,遇到错误
org.thymeleaf.exceptions.TemplateInputException: Error resolving template…
3.3.2 解决过程
- 在运行程序后,会在工程目录下生成一个bin文件夹
- 发现 bin 文件夹和 src文件夹的结构比较相似
- 在报错的时候,发现在 src/main/resources/templates 文件夹下添加的 index.html 并没有在 bin/templates 文件夹下
- 死马当活马医,将 index.html 文件拷贝一份到 bin/templates 目录下
- 重新运行,打开网页,运行成功了…
3.3.3 总结
-
bin目录下应该是存放的执行文件,索引资源时也是在该路径下索引,所以在src/main/resources/templates 路径下的 html 文件可能索引不到 —> 猜的… 为什么索引不到?是需要什么额外配置吗?
4. demo源码
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@SpringBootApplication
@RestController
public class DemoApplication {
@RequestMapping("/")
public String hello()
{
return "Hello";
}
@RequestMapping("/index")
public ModelAndView index()
{
ModelAndView modelView = new ModelAndView("index");
return modelView;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5. 后记
-
application.properties 文件一行没改,里面内容是空的 修改监听端口,在application.properties文件里添加(这里修改的文件是在bin目录下的才会生效,修改src目录下的不会生效,也不知道为啥): server.port=9000
