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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

程序猿修炼之道   2019-12-14 我要评论

题记:在学习了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。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们