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

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


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

1.不使用模板

1.1使用ModelAndView做为返回值

@Controller
public class LoginController {

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

资源路径以下:springboot

 

 启动项目后结果以下:session

1.2使用String做为返回值

@Controller
public class HelloController {

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

资源路径以下:mybatis

 

 启动项目后结果以下:app

 经过这两种方式能够发现controller类中返回的是在static中的login.html和hello.html。学习

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

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网址了code

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

2.4 启动项目

 

经过这两种方式能够发现controller类中返回的是在templates中的login.html和hello.html。xml

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

相关文章
相关标签/搜索