SpringMVC错误提示(三)

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

1.修改实体属性

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

 

 public class ProfileForm {
@Size(min = 2)
private String twitterHandle;
@Email
@NotEmpty
private String email;
@NotNull
private Date birthDate;
@NotEmpty
private 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.org
xmlns: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值