JSR 303是针对bean数据校验提出的一个规范。使用注解方式实现数据校验。
每个注解的用法这里就不多介绍,请移步JSR 303 - Bean Validation 介绍及最佳实践
笔者上面提到的JSR303是专家组成员向JCP提交的第一版Bean Validation,
主流Bean Validation使用Hibernate的实现,本文使用hibernate-validator
各个版本的规范对应关系如下:
- JSR 380 (Bean Validation 2.0)
- JSR 349 (Bean Validation 1.1)
- JSR 303 (Bean Validation 1.0)
JSR 303伴随着JAVAEE 6在2009年发布,Hibernate实现版本4.3.1.Final,Apache BVal实现版本0.5
JSR349伴随着JAVAEE 7在2013年发布,Hibernate实现版本5.1.1.Final,Apache BVal实现版本1.1.2
JSR380伴随着JAVAEE 8在2017年8月发布,完全兼容低版本的JAVASE,Hibernate实现版本6.0.1.Final,Apache BVal实现版本2.0.3(不太确定)
所以如果使用2.0规范,hibernate必须选择6.0.1以上版本
以下是Springmvc中Bean Validation配置过程:
1、在maven中添加规范与实现,缺一不可
<!--bean validation规范--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <!--bean validation规范实现--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.17.Final</version> </dependency>
2、在实体类类上使用注解
public class Post implements Serializable { private Integer pid; @Size(min = 5, message = "标题太短,无效,长度必须大于5") private String title; @Size(min = 20, message = "内容太短无效,长度必须大于20") private String content; //两个时间 private LocalDateTime publishTime; private LocalDateTime replyTime; //三个数量 private Integer replyCount; private Integer likeCount; private Integer scanCount; //两个外键 private Integer uid; private User user; @Min(value = 1,message = "请选择话题分类") //话题分类id必须大于0 private Integer tid; private Topic topic;
3、在Controller添加代码(@Valid @ModelAttribute)
@RequestMapping("publishPost.do") public String publishPost(@Valid @ModelAttribute Post post, BindingResult bindingResult, Errors errors, Model model,String action) { model.addAttribute("post",post); model.addAttribute("action",action); if(errors.hasErrors()){ FieldError fieldError = bindingResult.getFieldError(); System.out.println("Code:"+fieldError.getCode()+", object:"+fieldError.getObjectName() +", field:"+fieldError.getField()); List<Topic> topicList = topicService.listTopic(); model.addAttribute("topicList",topicList); return "post/editor"; }
spring-mvc.xml配置
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
前端代码:
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" trimDirectiveWhitespaces="true"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <form:form action="publishPost.do" method="post" commandName="post"> <input type="hidden" name="uid" value="${post.uid}"> <input type="hidden" name="pid" value="${post.pid}"> <%--<input type="hidden" name="user.uid" value="${post.uid}">--%> <input type="hidden" name="action" value="${action}"> <div class="pub-header"><span></span> 话题发布</div> <div class="pub-title"> <form:input path="title" placeholder="标题:一句话说明你遇到的问题或想分享的经验"/> <form:errors path="title" cssClass="has-error" element="div"/> ${error} </div> <div class="pub-topic"> <span>分类:</span> <div class="topic-list"> <form:select path="tid"> <form:option value="0">--请选择--</form:option> <c:forEach items="${topicList}" var="topic"> <option value="${topic.tid}" title="${topic.tid}"${topic.tid eq post.tid?'selected':''}>${topic.name}</option> </c:forEach> </form:select> <form:errors path="tid" cssClass="has-error" element="div"/> </div> </div> <div class="pub-textarea"> <div style="width: 920px;"> <form:textarea path="content" id="textarea" cssStyle="height: 300px;max-height: 1000px;"></form:textarea> <form:errors path="content" cssClass="has-error" element="div"/> </div> <button class="pub-button">发布</button> </div> </form:form>
效果
更新:
对于待校验的Bean属性,一定要使用NotNull约束。否则bean属性为null,也不会报错,插入数据时候就出错了,出现dao错误,让人摸不着头脑
更新后的JavaBean如下
package com.fc.model; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.time.LocalDateTime; @Data @NoArgsConstructor public class Post implements Serializable { private Integer pid; @Size(min = 5, message = "标题太短,无效,长度必须大于5") @NotNull(message = "标题必填") private String title; @Size(min = 20, message = "内容太短无效,长度必须大于20") @NotNull(message = "内容必填") private String content; //两个时间 private LocalDateTime publishTime; private LocalDateTime replyTime; //三个数量 private Integer replyCount; private Integer likeCount; private Integer scanCount; //两个外键 private Integer uid; private User user; @Min(value = 1,message = "请选择话题分类") //话题分类id必须大于0 @NotNull(message = "分类必选") private Integer tid; private Topic topic; private Post(Builder builder) { setPid(builder.pid); setUid(builder.uid); setTid(builder.tid); } @Override public String toString() { return "Post{" + "pid=" + pid + ", title='" + title + '\'' + ", content='" + content + '\'' + ", publishTime='" + publishTime + '\'' + ", replyTime='" + replyTime + '\'' + ", replyCount=" + replyCount + ", likeCount=" + likeCount + ", scanCount=" + scanCount + ", user=" + user + ", topic=" + topic + '}'; } public static final class Builder { private Integer pid; private Integer uid; private Integer tid; public Builder() { } public Builder pid(Integer pid) { this.pid = pid; return this; } public Builder uid(Integer uid) { this.uid = uid; return this; } public Builder tid(Integer tid) { this.tid = tid; return this; } public Post build() { return new Post(this); } } }
校验代码:
//发帖 @RequestMapping("publishPost.do") public String publishPost(@Valid Post post, BindingResult bindingResult, Errors errors, Model model,String action) { model.addAttribute("post",post); model.addAttribute("action",action); if(errors.hasErrors()){ FieldError fieldError = bindingResult.getFieldError(); System.out.println("Code:"+fieldError.getCode()+", object:"+fieldError.getObjectName() +", field:"+fieldError.getField()); List<Topic> topicList = topicService.listTopic(); model.addAttribute("post",post); model.addAttribute("topicList",topicList); return "post/editor"; } //更新文章 if("edit".equals(action)) { int effected = postService.updatePost(post); if(effected == 0) { model.addAttribute("topicList",topicService.listTopic()); model.addAttribute("error","更新失败"); return "post/editor"; } } //默认新增文章 Integer id = postService.publishPost(post); return "redirect:post.do?pid=" + id; }
参考内容:
https://blog.csdn.net/w_linux/article/details/80585468
https://docs.spring.io/spring/docs/3.0.0.RC2/spring-framework-reference/html/ch05s07.html
https://www.boraji.com/spring-4-mvc-form-validation-example-using-hibernate-validator
https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/html/validation.html
https://howtodoinjava.com/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。