Spring Boot入门二:使用ThymeLeaf+表单验证

来源:互联网 发布:mac 文件重命名 命令 编辑:程序博客网 时间:2024/06/06 07:53

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP,或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。


基本配置

  • 项目依赖:在pom.xml添加Spring Boot对ThymeLeaf的支持。
<dependency>      <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-thymeleaf</artifactId>  </dependency> 
  • view Resolver配置:在application.yml添加以下配置,包含编码、路径、后缀、关闭缓存等
spring:  thymeleaf:    encoding: UTF-8    mode: HTML5    prefix: classpath:/templates/    suffix: .html    check-template: true    cache: false

使用简单表单验证登录

  • 根据前面的配置,在src/main/resources下,新建templates文件夹-新建login.html
<!DOCTYPE html><html>    <head>        <meta charset="UTF-8"/>        <title>Insert title here</title>    </head>    <body>        <form action="login" method="post">            <p>姓名:<input type="text" name="username"/>            </p>            <p>密码:<input type="password" name="password"/>            </p>            <p><button>提交</button>            </p>        </form>    </body></html>
  • 新建实体类User,使用validator对信息进行验证
public class User {    private int id;    @NotEmpty(message="用户名不能为空")    private String username;    @NotEmpty(message="密码不能为空")    @Length(min=6, message="密码长度不能少于六位")    private String password;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}
  • 新建LoginController.java,包含两个mapping。/index路径负责引导用户到login.html,login路径首先用@Valid捕捉错误信息,并返回结果。ps:需要使用viewResolver的路径时,不能使用RestController注解。
@Controllerpublic class LoginController {    @RequestMapping(value="/index")    public String index() {        return "login";    }    @RequestMapping(value="/login")    public @ResponseBody User login(@Valid User user, BindingResult result, Model model) {        if (result.hasErrors()) {            List<ObjectError> error = result.getAllErrors();            for (ObjectError e : error) {                System.out.println(e);            }            return null;        }        return user;    }}
  • 启动项目,在浏览器输入http://localhost:8080/index。
    index
    输入错误可在console看到错误信息,否则跳转页面。
    login
原创粉丝点击