springboot学习13

springboot
1、支持的模板选项:
表1.1

模板 Spring Boot starter 依赖
FreeMarker spring-boot-starter-freemarker
Groovy Templates spring-boot-starter-groovy-templates
JavaServer Page(JSP) None (provided by Tomcat or Jetty)
Mustache spring-boot-starter-mustache
Thymeleaf spring-boot-starter-thymeleaf
在表 1.1 中请注意,JSP 在构建中不需要任何特殊的依赖关系。这是因为 servlet 容器本身(默认情况下是 Tomcat)实现了 JSP 规范,因此不需要进一步的依赖关系。

但是如果选择使用 JSP,就会遇到一个问题。事实证明,Java servlet 容器 —— 包括嵌入式 Tomcat 和 Jetty 容器 —— 通常在 /WEB-INF 下寻找 jsp。
但是如果将应用程序构建为一个可执行的 JAR 文件,就没有办法满足这个需求。因此,如果将应用程序构建为 WAR 文件并将其部署在传统的 servlet 容器中,那么 JSP 只是一个选项。

如果正在构建一个可执行的 JAR 文件,必须选择 Thymeleaf、FreeMarker 或表 1.1 中的其他选项之一

启用/禁用模板缓存的属性

模板 缓存使能属性
Freemarker spring.freemarker.cache
Groovy Templates spring.groovy.template.cache
Mustache spring.mustache.cache
Thymeleaf spring.thymeleaf.cache

默认情况下,所有这些属性都设置为 true 以启用缓存。
可以通过将其缓存属性设置为 false 来禁用所选模板引擎的缓存。
例如,要禁用 Thymeleaf 缓存,请在 application.properties 中添加以下行:

spring.thymeleaf.cache = false
在将应用程序部署到生产环境之前,一定要删除这一行(或将其设置为 true)。
另一种选择是在 `profile` 文件中设置属性。
一个更简单的选择是使用 Spring Boot 的 DevTools。

2、引入视图模板库依赖项:
如:thymeleaf

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

选择想要的视图模板库,将其作为依赖项添加到构建中,然后开始在 /templates 目录中(在 Maven 或 Gradl 构建项目的 src/main/resources 目录下。
Spring Boot 将检测选择的模板库,并自动配置所需的组件来为 Spring MVC 控制器提供视图。

如:Mustache

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

3、常用属性:
Thymeleaf 模板只是 HTML 与一些额外的元素属性,指导模板在渲染请求数据。

th:text

<p th:text="${message}">placeholder message</p>

th:eachth:value

<div th:each="ingredient : ${wrap}">
    <input name="ingredients" type="checkbox" th:value="${ingredient.id}" />
    <span th:text="${ingredient.name}">ingredient</span><br/>
</div>

th:src

<img th:src="@{/images/xxx.png}"/>

th:object:

<form method="POST" th:object="${design}">
</form>

th:action:

 <form method="POST" th:action="@{/orders}" th:object="${order}">
 </form>

th:href

<link rel="stylesheet" th:href="@{/styles.css}" />

th:if:

<div th:if="${#fields.hasErrors()}">
</div>

th:field:

<input type="text" th:field="*{name}"/>

4、验证表单输入:

Spring 支持 Java's Bean Validation API(JSR-303)。
这使得声明验证规则比在应用程序代码中显式地编写声明逻辑更容易。
使用 Spring Boot,不需要做任何特殊的事情来将验证库添加到项目中,
因为 Validation API 和 Validation API 的 Hibernate
实现作为Spring Boot web 启动程序的临时依赖项自动添加到了项目中。

在 Spring MVC 中应用验证,需要这样做:

1、对要验证的类声明验证规则:
2、指定验证应该在需要验证的控制器方法中执行;
3、修改表单视图以显示验证错误。
Validation API 提供了几个可以放在域对象属性上声明验证规则的注释。
Hibernate 的 Validation API 实现甚至添加了更多的验证注释

@NotNull@Size

@Data
public class Demo {
    
    
	//要求 name 属性不为 null,同时你声明它应该有一个值是至少 5 个字符的长度
    @NotNull
    @Size(min=5, message="Name must be at least 5 characters long")
    private String name;
    
    @Size(min=1, message="You must choose at least 1 hobby")
    private List<String> hobbys;
}

Hibernate Validator的其他验证:
空白字段验证,如:。
@NotBlank

 @NotBlank(message="Street is required")

@CreditCardNumber

 @CreditCardNumber(message="Not a valid credit card number")

@Pattern

@Pattern(regexp="^(0[1-9]|1[0-2])([\\/])([1-9][0-9])$",
             message="Must be formatted MM/YY")

@Digits

@Digits(integer=3, fraction=0, message="Invalid CVV")
要验证提交的 Taco,需要将 Java Bean Validation API 的 @Valid 注释添加到 
Controller 的 processMethod() 方法的 Taco 参数中。
@PostMapping
public String processDesign(@Valid Taco design, Errors errors) {
    
    
    if (errors.hasErrors()) {
    
    
        return "design";
    }
    //.....
 }

5、Thymeleaf 通过 fields 属性及其 th:errors 属性提供了对 Errors 对象的便捷访问。

如:th:if 属性来决定是否显示 ,
fields 属性的 hasErrors() 方法。

<span class="validationError"
      th:if="${#fields.hasErrors('ccNumber')}"
      th:errors="*{ccNumber}">CC Num Error</span>

6、视图控制器
ViewControllerRegistry,可以使用它来注册一个或多个视图控制器。

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    
 	// ...
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        registry.addViewController("/").setViewName("home");
    }
}

也可以通过扩展现有的配置类,可以避免创建新的配置类。

@SpringBootApplication
public class TacoCloudApplication implements WebMvcConfigurer {
    
    
	public static void main(String[] args) {
    
    
        SpringApplication.run(TacoCloudApplication.class, args);
    }
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        registry.addViewController("/").setViewName("home");
    }
}

猜你喜欢

转载自blog.csdn.net/tongwudi5093/article/details/113784945