首页 > 其他分享 >SpringMVC中实现Bean Validation(JSR 303 JSR 349 JSR 380)

SpringMVC中实现Bean Validation(JSR 303 JSR 349 JSR 380)

时间:2022-10-13 22:03:15浏览次数:86  
标签:SpringMVC spring 303 private JSR Integer post validation model

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

3、在Controller添加代码(@Valid @ModelAttribute)

)
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>

效果

SpringMVC中实现Bean Validation(JSR 303 JSR 349 JSR 380)_java

 

更新:

对于待校验的Bean属性,一定要使用NotNull约束。否则bean属性为null,也不会报错,插入数据时候就出错了,出现dao错误,让人摸不着头脑

SpringMVC中实现Bean Validation(JSR 303 JSR 349 JSR 380)_spring_02

 

 

 更新后的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://stackoverflow.com/questions/1384968/is-there-an-implementation-of-jsr-303-bean-validation-available​

​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​

​http://websystique.com/springmvc/spring-4-mvc-form-validation-with-hibernate-jsr-validator-resource-handling-using-annotations/​

​https://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api​

​https://howtodoinjava.com/spring-mvc/spring-bean-validation-example-with-jsr-303-annotations/​

​https://www.iteye.com/blog/jinnianshilongnian-1990081​

标签:SpringMVC,spring,303,private,JSR,Integer,post,validation,model
From: https://blog.51cto.com/u_296714/5754727

相关文章

  • 一、springmvc之helloworld
    一、jar包下载:查找springframework的下载地址: ​​github spring-framework​​​上可以找到对应的 AccesstoBinaries跳转到​​wiki ​​​ ,wiki中给出了Downlo......
  • 十一(一)、springMVC之异常处理@ExceptionHandler注解
    一、概述:springMVC通过HandlerExceptionResolver处理程序的异常,异常包括Handler映射、数据绑定以及目标方法执行时发生的异常;springMVC提供的HandlerExceptionResolver的实......
  • SpringMvc第一天学习 restful 风格即其中的一些配置及其注解
    在先知道springMVC之前我们先了解一下MVC模式MVC模式是表现层的一种设计模式M代表着模型(model)V代表着视图(View)C代表着控制器(controller)使用MVC的目的是将M和V......
  • SpringMVC简介
    SpringMVC简介大部分Java应用都是Web应用,展现层是WEB应用不可忽略的重要环节.Spring为了展现层提供了一个优秀的WEB框架-SpringMVC . 和众多的其他WEB框架一样,它基于......
  • Springmvc简介
    ​SpringMVC简介大部分Java应用都是Web应用,展现层是WEB应用不可忽略的重要环节.Spring为了展现层提供了一个优秀的WEB框架-SpringMVC . 和众多的其他WEB框架一样,......
  • 直播平台怎么搭建,SpringMVC-登录验证判断
    直播平台怎么搭建,SpringMVC-登录验证判断1.拦截器 packagecom.kuang.config;importorg.springframework.web.servlet.HandlerInterceptor;importjavax.servlet.http......
  • springMVC学习笔记
    为什么要学习springMVC,springMVC和struts2的比较SpringMVC与Struts2区别对比项目SrpingMVCStruts2优势国内市场情况有大量用户,一般新项目启动都会选用springmvc有部分老用户......
  • springMVC的工作流程
    一.springMVC的常用组件1)DispatcherServlet是一种前端控制器,由框架提供。作用:统一处理请求和响应。除此之外还是整个流程控制的中心,由DispatcherServlet来调用其他组......
  • SpringMVC之参数验证
    SpringMVC之参数验证目录SpringMVC之参数验证一、为什么使用参数验证1.1、参数验证作用二、怎么使用参数验证2.1、小结三、具体操作流程3.1、在pojo类中添加需要使用的注......
  • SpringMVC
    SpringMVC:https://www.cnblogs.com/henuliulei/p/14643052.html作用:1.springmvc请所有的请求都提交给DispatcherServlet,它会委托应用系统的其他模块负责负责对请求进行......