【 SpringBoot 实例 】—— 默认访问首页

Fork me on Gitee

为什么访问不到 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
在这里插入图片描述

补充:修改 页面的资源引用

在这里插入图片描述

扫描二维码关注公众号,回复: 5424751 查看本文章

上面的资源引入,都是静态资源下的,我么可以使用 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/crudhttp://localhost:8080/crud/index.html
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42112635/article/details/88117459