![](/img/trans.png)
[英]@Min and @Max validation is not working of hibernate validator package in spring boot
[英]Validation not working on spring boot and hibernate
我是 spring boot 和 hibernate 的新手。我已經聲明了一個模型類 Office,它是:
package com.ashwin.officeproject.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
@Entity
@Table(name = "office")
public class Office {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long officeId;
@NotEmpty(message = "{officename.notempty}")
private String officeName;
@NotNull
private int officeNumber;
/*@Size(min = 8, max = 72, message = "Your offc address between 8 and 72 characters long")*/
/*@NotEmpty(message = "Please provide a offc name")*/
private String officeAddress;
public Office() {
}
//ommitted getters and setters
}
我已宣布我的第一個主要起始課程為:
package com.ashwin.officeproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@SpringBootApplication
public class OfficeProjectApplication {
public static void main(String[] args) {
SpringApplication.run(OfficeProjectApplication.class, args);
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource
= new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Bean
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
}
我的控制器類是:
package com.ashwin.officeproject.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ashwin.officeproject.model.Office;
import com.ashwin.officeproject.repository.OfficeRepsitory;
@Controller
public class MainController {
@Autowired
OfficeRepsitory officeRepository;
@RequestMapping(value = { "/office"}, method = RequestMethod.GET)
public String office(Model model) {
model.addAttribute("offices", new Office());
return "office";
}
@RequestMapping(value = "/addOffice", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("offices") Office office,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error";
}
officeRepository.save(office);
model.addAttribute("offices", new Office());
return "office";
}
}
我有一個 office.jsp 頁面,它是:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<jsp:include page="./header.jsp" />
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<form:form method="POST" action="/addOffice" modelAttribute="offices" >
<table>
<tr>
<td><form:label path="officeName">Name</form:label></td>
<td><form:input path="officeName"/></td>
<form:errors path = "officeName" cssClass = "error" />
</tr>
<tr>
<td><form:label path="officeNumber">Number</form:label></td>
<td><form:input path="officeNumber"/></td>
</tr>
<tr>
<td><form:label path="officeAddress">
Address</form:label></td>
<td><form:input path="officeAddress"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<jsp:include page="./footer.jsp" />
我的 pom.xml 是:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ashwin</groupId>
<artifactId>OfficeProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>OfficeProject</name>
<description>OfficeProject</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
當我單擊提交按鈕時,如果表單中的輸入字段為空,我想驗證我的表單並在輸入字段下方顯示消息,例如“請提供有效的辦公室名稱” 。但是發生的事情是當我點擊提交按鈕然后它會轉到我的 error.jsp 頁面,但它沒有顯示我在上面聲明的任何驗證消息。我的錯誤頁面顯示是:
錯誤.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<p>Error</p>
</body>
</html>
我在 eclipse 的控制台中也沒有收到任何錯誤。當我的表單字段為空時,它只是在 error.jsp 頁面中重定向我。
似乎 jar 沖突問題,因為org.hibernate.validator:hibernate-validator:jar(javax.validation:validation-api:jar is part of hibernate validator)
的一部分org.hibernate.validator:hibernate-validator:jar(javax.validation:validation-api:jar is part of hibernate validator)
是 spring web 依賴項的一部分,因此無需添加可能會發生沖突的額外依賴項,因此建議刪除以下依賴項並通過全新安裝( mvn clean install
)再次構建項目。
刪除以下依賴項:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.12.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
並確保您訪問以下錯誤消息:不需要大括號和屬性名稱與您定義的實際消息屬性名稱匹配。(駝峰式名稱與名稱有關)。
@NotEmpty(message = "officename.notempty")
我從 Spring Boot 2.2.4.RELEASE 遷移到 2.4.2,只要我做了更改,驗證就開始失敗。
開始失敗的原因是從 Spring Boot 2.3 版的 web 模塊中刪除了驗證依賴項。
我進行了以下更改以運行驗證。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation.api}</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>${jboss.logging.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>${fasterxml.classmate.version}</version>
</dependency>
相應地更改版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.