Spring Boot中,

静态资源(css、js、图片等)默认放在resources/static下面。如果要修改默认存放目录,可以通过设置属性spring.mvc.static-path-pattern来实现。

模板文件默认放在 templates目录下

Spring boot支持使用模板来开发web应用,支持的模板类型包括

FreeMarker

Groovy

Thymeleaf

Mustache

Spring boot不建议使用jsp开发web。


本文使用Thymeleaf作为模板引擎来开发web项目。

一、在application.properties中设置Thymeleaf相关属性

#Checkthatthetemplateexistsbeforerenderingit.spring.thymeleaf.check-template=true#Checkthatthetemplateslocationexists.spring.thymeleaf.check-template-location=true#Content-TypevaluewrittentoHTTPresponses.spring.thymeleaf.content-type=text/html#EnableThymeleafviewresolutionforWebframeworks.spring.thymeleaf.enable=true#Templatefilesencoding.spring.thymeleaf.encoding=UTF-8#Comma-separatedlistofviewnamesthatshouldbeexcludedfromresolution.spring.thymeleaf.exclude-view-names=index#PrefixthatgetsprependedtoviewnameswhenbuildingaURL.spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html#Templatemodetobeappliedtotemplates.SeealsoStandardTemplateModeHandlers.spring.thymeleaf.mode=HTML5#Disabletemplatecaching.spring.thymeleaf.cache=false


二、在pom.xml添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>


三、在resources目录下创建templates文件夹,并添加模板html

test.html

<!DOCTYPEhtml><html><head><metacharset="UTF-8"><title>Inserttitlehere</title></head><body>姓名:<spanth:text="${user.username}"></span></br>邮箱:<spanth:text="${user.email}"></span></br>昵称:<spanth:text="${user.nickname}"></span></body></html>


四、增加Controller

@ControllerpublicclassTemplatesController{@AutowiredprivateUserServiceuserService;@RequestMapping("/index")Stringtest(ModelMapmap){map.addAttribute("key","thymeleaf");return"index";}@RequestMapping("/test")publicStringtestThymeleaf(ModelMapmap){map.addAttribute("user",userService.selectByPrimaryKey(1));return"test";}}


五、运行结果

到这里,Spring Boot + Mybatis +Spring MVC环境就搭建完成了


完整环境下载地址:https://github.com/CatherineHu/Spring-Boot-Mybatis-MVC