Spring boot返回静态页面初识

转发请注明来源,谢谢!
背景:需要使用Spring boot做一点前端,不知道怎么访问HTML。。。一番疯狂搜索,看到有直接各种版本,但自己模仿实现又不行,一番焦灼,做点总结


一.不使用任何模板框架(thymeleaf等)返回HTML
这里写图片描述
说明: Spring Boot 默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources),借用的其他博客说明,我只测试了static,其他路径有兴趣的可以试试,也就是说这些路径下的资源都是静态的。
1. maven配置,新建项目,默认配置

```
    <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.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
    <!-- 下面配置可以不用 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>1.5.8.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>
```

2. 配置文件application第一个是空的,第二个是我的数据库配置,和本次测试无关
3. 直接controller返回static路径下的HTML(indexs.html内容在最后)

```
@RequestMapping(value = "/indexs",method = RequestMethod.GET)
//@ResponseBody
public String showIndexs(){
    return "/indexs.html";
}
```

4. 不使用模板默认访问static下的资源,返回必须要带.html,必须是/indexs.html(亲测)
5. 说明一点,这里注解应该用@Controller,而不是@RestController(会直接返回一个字符串而不是HTML内容),区别自己查咯

二.使用thymeleaf模板返回HTML

  1. 添加maven配置

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
  2. 修改Controller,下面三种方式都可行,亲测,注意返回的文件路径

    @RequestMapping(value = "/html",method = RequestMethod.GET)
    public ModelAndView showlist(){
        ModelAndView mv =  new ModelAndView("index");
        return mv;
    }
    
    @RequestMapping(value = "/heheda",method = RequestMethod.GET)
    //@ResponseBody
    public String showString(){
        return "index";
    }
    
    @RequestMapping("/hello")
    public String helloHtml(HashMap<String, Object> map) {
        map.put("hello", "欢迎进入HTML页面");
        return "/index";
    }
  3. return 有没有“/”都可以;不需要配置任何东西(正式项目可能需要配置缓存等等其他);不能带.html后缀

  4. index.html和indexs.html内容一样

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>第一个HTML页面</title>
    </head>
    <body>
    <h1>Hello Spring Boot!!!</h1>
    <p th:text="${hello}"></p>
    </body>
    </html>

    理解还是很浅,待以后深入了再来做补充。
    有问题欢迎私信或者评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值