Springboot: thymeleaf
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/thymeleaf?characterEncoding=UTF-8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: coalesce devtools: restart: enabled: true poll-interval: 1s quiet-period: 400ms livereload: enabled: true port: 35729 add-properties: true thymeleaf: cache: false # 默认true, 开发设为false prefix: classpath:/templates/ # thymeleaf 模板前缀目录, 不带/,不能访问默认首页 suffix: .html # 模板后缀 check-template: true check-template-location: true enabled: true encoding: UTF-8 mode: HTML mvc: servlet: path: /servlet load-on-startup: 1 static-path-pattern: /static/** format: date: yyyy-MM-dd date-time: yyyy-MM-dd'T'HH:mm:ss time: HH:mm:ss web: resources: static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/
配置类:
package us.transcode.thymeleaf.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer{ @Override // 无需为每个访问thymeleaf模板页面, 单独写controller public void addViewControllers(ViewControllerRegistry registry){ // viewController: 请求路径 viewName: 跳转视图 registry.addViewController("varlet").setViewName("varlet"); registry.addViewController("error").setViewName("error"); registry.addViewController("hello").setViewName("hello"); registry.addViewController("hello").setViewName("cors"); registry.addViewController("cors").setViewName("cors"); } }
controller:
package us.transcode.thymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @Controller public class DemoController{ @RequestMapping("demo") public String demo(HttpServletRequest httpServletRequest, Model model){ String name = "proofread"; httpServletRequest.setAttribute("name", name); model.addAttribute("age", 55); return "demo"; // 返回resources/templates/demo.html } }