zoukankan      html  css  js  c++  java
  • 上手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。

  • 相关阅读:
    如何安装一个高可用K3s集群?
    如何设置一个生产级别的高可用etcd集群
    从架构到部署,全面了解K3s
    这应该是最适合国内用户的K3s HA方案
    在K3s上使用Kong网关插件,开启K3s的无限可能!
    AngularJS 遗留项目的升级改造之路(一)
    Rancher首席架构师解读Fleet:它何以管理百万集群?
    资深首席架构师预测:2021年云计算的8个首要趋势
    简单4步,利用Prometheus Operator实现自定义指标监控
    当年,我的架构师之路差点完蛋,幸亏了它
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/12037746.html
Copyright © 2011-2022 走看看