• 上手spring boot项目(一)之如何在controller类中返回到页面


    题记:在学习了springboot和thymeleaf之后,想完成一个项目练练手,于是使用springboot+mybatis和thymeleaf完成一个博客系统,在完成的过程中出现的一些问题,将这些问题记录下来,作为自己的学习心得。在这先感谢群主TyCoding的Tumo项目,虽然本人实在太菜了,好些地方看不懂,但还是使我受益匪浅。


    在controller类中返回到页面中一共有两种方式,使用thymeleaf模板引擎的方式和不使用模板的方式(即controller的返回值为ModelAndView或者String)。在controller类中返回值为ModelAndView或者String,二者的区别就在于ModelAndView能够像session一样存储一些属性。

    1.不使用模板

    1.1使用ModelAndView作为返回值

    @Controller
    public class LoginController {
    
        @RequestMapping(value = "/login")
        public ModelAndView login(){
            ModelAndView mv = new ModelAndView();
            mv.setViewName("/login.html");
            return mv;
        }
    }

    资源路径如下:

     

     启动项目后结果如下:

    1.2使用String作为返回值

    @Controller
    public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
    return "/hello.html";
    }
    }

    资源路径如下:

     

     启动项目后结果如下:

     通过这两种方式可以发现controller类中返回的是在static中的login.html和hello.html。

    结论:springboot中静态资源默认是放在static路径下的,换而言之就是html等页面的根路径是static

    2.使用thymeleaf模板引擎

    2.1 在pom文件中引入依赖

     2.2 在application.yml文件中添加配置信息

    # thymeleaf
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.check-template-location=true
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.content-type=text/html
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.cache=false

    2.3 编写controller类&html代码

    由于这里的controller类和html页面路径与前面的一样,我就不贴上代码了。由于只是演示展示页面,所以就未在html标签中添加thymeleaf网址了

    <html lang="en" xmlns:th="http://www.thymeleaf.org">

    2.4 启动项目

     

    通过这两种方式可以发现controller类中返回的是在templates中的login.html和hello.html。

    结论:springboot中整合templates之后静态资源默认是放在templates路径下的,也就是html等页面的根路径是templates。

  • 相关阅读:
    if __name__ == '__main__' 用法理解
    VSCode 使用
    sys.argv用法简介
    [Python3] RSA的加解密和签名/验签实现 -- 使用pycrytodome
    python requests 超时与重试
    collections模块之defaultdict()与namedtuple()方法简单介绍
    setdefault函数的用法及理解
    python并发编程之IO模型 同步 异步 阻塞 非阻塞
    django+uWSGI+nginx的工作原理流程与部署过程
    Nginx静态服务配置---详解root和alias指令
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/12037746.html
Copyright © 2020-2023  润新知