springboot表单验证

勾选web,thymeleaf,lombok

pom.xml添加

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-el</artifactId>
</dependency>
PersonForm

@Getter
@Setter
@ToString
public class PersonForm {
    @NotNull
    @Size(min=2,max = 30)
    private String name;
    @NotNull
    @Min(18)
    private Integer age;
}
WebController

@Controller
public class WebController extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/")
    public String showForm(PersonForm personForm){
        return "form";
    }

    @PostMapping("/")
    public String checkPersonInfo(@Valid PersonForm personForm, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return "form";
        }
        return "redirect:/results";
    }
}
form.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>登录注册</title>
</head>
<body>
    <form action="#" th:action="@{/}" th:object="${personForm}" method="post">
        <table>
            <tr>
                <td>姓名:</td>
                <td><input type="text" th:field="*{name}"/></td>
                <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" th:field="*{age}"/></td>
                <td th:if="${#fields.hasErrors('age')}" th:error="*{age}">未满18岁禁止入内</td>
            </tr>
            <tr>
                <td><button type="submit">提交</button> </td>
            </tr>
        </table>
    </form>
</body>
</html>
result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>results</title>
</head>
<body>
本网站成人内容收集于全世界的互联网,网站在美国进行维护,受美国法律保护
</body>
</html>
鸣谢:http://blog.youkuaiyun.com/forezp/article/details/71023817

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值