表单验证

我们不希望用户输入非法或空的信息,这样的话,就要在ProfileForm中增加一些校验逻辑:

public class ProfileForm
{
    @NotEmpty
    @Size(min=2)
    private String name;
    @NotEmpty
    @Email
    private String email;
    private List<String>tastes = new ArrayList<>();
可以看到,我们新增了一些校验限制,这些注解来源于JSR-303规范,他详细规定了bean的校验功能.这个规范最流行的实现是hibernate-validator,他已经包含在了spring boot之中.
我们使用了来自

javax.validation.constraints
包中的注解
为了让校验功能运行起来,我们还需要添加一些内容,首先,控制器需要声明在表单提交时,他希望得到一个合法的模型.在代表表单的参数上添加
@Valid ProfileForm profileForm
就能实现该功能

public String saveProfile(@Valid ProfileForm profileForm,BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            return "profile/profile";
        }
        System.out.println("save ok"+profileForm.getName());
        return "redirect:/profile";
    }
需要注意的是,如果表单中包含错误的话,我们并没有为用户进行重定向.这样的话能够在同一个web页面中展现错误信息.
在视图中,表单标签开始的地方添加如下代码:

    name:<input type="text" id="name" th:field="${profileForm.name}"/>
    <span th:errors="*{name}">Error</span>
    <br/>
    email:<input type="text" id="email" th:field="${profileForm.email}"/><br/>
    <span th:errors="*{email}">Error</span>
自定义错误信息
spring boot会负责为我们创建信息源bean,信息默认的位置是src/main/resources/message.properties
创建一个这样的bundle,并添加如下文本:

NotEmpty.profileForm.name=hahaha
NotEmpty.profileForm.email=hehehe
在开发期,将信息源配置为每次都重新加载bundle是非常便利的,添加如下属性到application.properties:

spring.messages.cache-duration.seconds=-1
重启服务
但是,这种方式的缺点在于他无法与国际化功能兼容