JSR303实现数据校验案例
1、导包
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
2、实体类
package com.yl.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
/**
* 图书实体类
*/
@Data
@NoArgsConstructor
public class Book implements Serializable {
private Integer id;
@NotEmpty(message = "书名不能为空")
private String name;
private String author;
private Date date;
private Float price;
}
3、表单
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: aq
Date: 2020/10/26
Time: 21:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add</title>
</head>
<body>
<form:form modelAttribute="book" action="${pageContext.servletContext.contextPath}/book/add" method="post">
书名:<form:input path="name"/><form:errors path="name" cssStyle="color: red"></form:errors><br>
作者:<form:input path="author"/><br>
出版日期:<form:input path="date"/><br>
价格:<form:input path="price"/><br>
<button type="submit">添加</button>
</form:form>
</body>
</html>
4、控制器
package com.yl.controller;
import com.github.pagehelper.PageInfo;
import com.yl.bean.Book;
import com.yl.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.List;
/**
* 图书控制器类
*/
@Controller
@RequestMapping("/book")
@SessionAttributes(value = {"pageBook","queryBook"}, types = {PageInfo.class, String.class, Book.class})
public class BookController {
@Autowired
private IBookService bookService;//图书业务层对象
/**
* 添加图书
*/
@RequestMapping("/add")
public ModelAndView add(@Valid Book book, Errors errors,SessionStatus sessionStatus) {
ModelAndView modelAndView=new ModelAndView();
if (errors.hasErrors()){
modelAndView.setViewName("add");
return modelAndView;
}
//调用业务层添加图书方法
bookService.add(book);
return queryByCondition(null,1);
}
/**
*添加图书跳转页面
*/
@RequestMapping("/addSkip")
public ModelAndView addSkip(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("book",new Book());
modelAndView.setViewName("add");
return modelAndView;
}
}
注意:表单的modelAttribute属性值是从requsetScope中传过来的,即必须先请求控制器,在控制器中给modelAttribute赋值才能使用;默认是command的属性值,也可以自己赋值。