vscode + springboot + HTML 搭建服务端(二)

1. vscode环境搭建和工程创建请参考上一篇文章

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…
在这里插入图片描述

  • 查找了各种解决方案,都不行。查找的解决方案参考以下链接,大体的解决办法都包含在里面了,可惜对我无用:
    https://blog.csdn.net/qq_38487209/article/details/125873532
    https://www.cnblogs.com/DrAyaneShindou/p/13683358.html
3.3.2 解决过程
  1. 在运行程序后,会在工程目录下生成一个bin文件夹
    在这里插入图片描述

  2. 发现 bin 文件夹和 src文件夹的结构比较相似

  3. 在报错的时候,发现在 src/main/resources/templates 文件夹下添加的 index.html 并没有在 bin/templates 文件夹下

  4. 死马当活马医,将 index.html 文件拷贝一份到 bin/templates 目录下
    在这里插入图片描述

  5. 重新运行,打开网页,运行成功了…
    在这里插入图片描述

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
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

同学小张

如果觉得有帮助,欢迎给我鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值