为什么访问不到 templates/index.html
启动项目,浏览器输入 http://localhost:8080/
上面访问不到 index.html
,是由于 默认实在静态资源下面去找 index.html
,而我们的 index.html
,在 templates 目录下面。
如果我们在 resources
下新建一个目录 public
,下面新建 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello YANG!</h1>
</body>
</html>
启动项目,浏览器输入 http://localhost:8080/
访问到 templates/index.html
的方式
方式一:写一个 IndexController
处理的请求为
{"/","/index.html"}
,返回"index"
,会寻找模板下的index.html
package cn.ys.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping({"/","/index.html"})
public String showIndex(){
return "index";
}
}
测试:启动启动项,浏览器输入 http://localhost:8080/ ,报错
原因:访问的是模板下的 index.html
,需要导入 thymeleaf
模板,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
再次启动项目,浏览器输入 http://localhost:8080/ 、http://localhost:8080/index.html
方式二:配置一个 MyMvcConfig
package cn.ys.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
// 所有的WebMvcConfigurerAdapter组件都会一起起作用
@Bean // 将组件注册在容器
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
};
return adapter;
}
}
再次启动项目,浏览器输入 http://localhost:8080/ 、http://localhost:8080/index.html
补充:修改 页面的资源引用
上面的资源引入,都是静态资源下的,我么可以使用 webjars
参考:https://blog.csdn.net/weixin_42112635/article/details/88097203
pom
导包
<!-- 引入bootstrap -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
修改 index.html
再次启动项目,浏览器输入 http://localhost:8080/ 、http://localhost:8080/index.html
th
语法的好处
如果有一天项目的访问名变了,会自动加入访问路径
server:
servlet:
context-path: /crud
再次启动项目,浏览器输入 http://localhost:8080/crud 、http://localhost:8080/crud/index.html