SpringMVC错误提示(三)

来源:互联网 发布:淘宝买airpods靠谱吗 编辑:程序博客网 时间:2024/06/05 11:11

在上一节中,我们已经讲了,在客户端我们需要对用户输入的信息进行校验。那么这个功能应该怎样去实现呢?在这一节中我们将会讲解。

1.修改实体属性

       我们希望用户输入一些无效的或空的信息,这就是为什么我们需要对ProfileForm类作相应的修改。修改如下。

 

 public class ProfileForm {@Size(min = 2)private String twitterHandle;@Email@NotEmptyprivate String email;@NotNullprivate Date birthDate;@NotEmptyprivate List<String> tastes = new ArrayList<>();}

在这里我们作了些有效的强制限制。这些注解都是来自JSR-303的规格。这个规格是贯彻于hibernate-validator的,也包括Spring Boot.

2.修改控制逻辑

在ProfileController中,我要添加下面的修改。

 @RequestMapping(value="/profile", params = {"save"}, method = RequestMethod.POST)public String saveProfile(@Valid ProfileForm profileForm, BindingResult bindingResult){    //提交信息的错误    if (bindingResult.hasErrors())    {        return "profile/profilePage";    }    System.out.println("save ok" + profileForm);    return "redirect:/profile";}

3.视图层的修改

为了将控制层报同的错误可以友好地在视图层里显示,我们需要修改profilePage.html的页面。修改后的代码如下。

<!DOCTYPE html><html xmlns:th=http://www.thymeleaf.orgxmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"layout:decorator="layout/default"><head lang="en"><title>Your Profile</title></head><body><div class="row" layout:fragment="content"><h2 class="indigo-text center">Personal info</h2><form th:action="@{/profile}" th:object="${profileForm}"method="post" class="col m8 s12 offset-m2"><div class="row"><div class="input-field col s6"><input th:field="${profileForm.twitterHandle}"id="twitterHandle" type="text" th:errorclass="invalid"/><label for="twitterHandle">Twitter handle</label><div th:errors="*{twitterHandle}" class="redtext">Error</div></div><div class="input-field col s6"><input th:field="${profileForm.email}" id="email"type="text" th:errorclass="invalid"/><label for="email">Email</label><div th:errors="*{email}" class="red-text">Error</div></div></div><div class="row"><div class="input-field col s6"><input th:field="${profileForm.birthDate}"id="birthDate" type="text" th:errorclass="invalid" th:placeholder="${dateFormat}"/><label for="birthDate">Birth Date</label><div th:errors="*{birthDate}" class="red-text">Error</div></div></div><div class="row s12"><button class="btn indigo waves-effect waves-light"type="submit" name="save">Submit<i class="mdi-content-send right"></i></button></div></form></div></body></html>

4.总结

最后,你将会看到的错误提示信息如下。


 对于这样的一些提示信息,我们最好是不要写成固定的同,我们写成可配置的文件中。所以接下来我们需要对这些信息进行重新修改。将在下一节中讲解。


源码路径:git@github.com:owenwilliam/masterSpringMVC.git


0 0
原创粉丝点击