English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La verifica Spring MVC è utilizzata per limitare l'input fornito dall'utente. Per verificare l'input dell'utente, Spring 4 o versioni successive supportano e utilizzano l'API di verifica Bean. Può verificare contemporaneamente applicazioni server-side e client-side.
L'API di verifica Bean è una specifica Java che può essere utilizzata per applicare restrizioni al modello oggettuale attraverso annotazioni. Qui possiamo verificare la lunghezza, i numeri, gli espressioni regolari, ecc. Inoltre, possiamo fornire verifiche personalizzate.
Poiché l'API di verifica Bean è solo una specifica, è necessario implementarla. Pertanto, per questo, utilizza Hibernate Validator. Hibernate Validator è una implementazione completamente compatibile con JSR-303/309, che consente di esprimere e verificare le restrizioni dell'applicazione.
Facciamo un'occhiata a alcune annotazioni di verifica comuni.
Commento | Descrizione |
@NotNull | Determina che il valore non può essere vuoto. |
@Min | Determina che il numero deve essere uguale o superiore al valore specificato. |
@Max | Determina che il numero deve essere uguale o inferiore al valore specificato. |
@Size | Determina che la dimensione deve essere uguale al valore specificato. |
@Pattern | Determina se la sequenza segue l'espressione regolare specificata. |
In questo esempio, abbiamo creato un modulo di input con campi di input semplici. In questo caso, (*) indica che è necessario inserire il campo corrispondente. Altrimenti, la tabella genererà un errore.
pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jasper</artifactId> <version>9.0.12</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.13.Final</version> </dependency>
Employee.java
package com.w3codebox; import javax.validation.constraints.Size; public class Employee { private String name; @Size(min=1, message="richiesto") private String pass; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
Nella classe del controller:
@ValidI commenti applicano le regole di convalida all'oggetto fornito. BindingResult L'interfaccia contiene i risultati della convalida.
package com.w3codebox; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class EmployeeController { @RequestMapping("/hello") public String display(Model m) { m.addAttribute("emp", new Employee()); return "viewpage"; } @RequestMapping("/helloagain") public String submitForm(@Valid @ModelAttribute("emp") Employee e, BindingResult br) { if(br.hasErrors()) { return "viewpage"; } else { return "final"; } } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Provide support for component scanning --> <context:component-scan base-package="com.w3codebox" /> <!-- Provide support for conversion, formatting and validation --> <mvc:annotation-driven/> <!-- Define Spring MVC view resolver --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
index.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <body> <a href="hello">Clicca qui...</a> </body> </html>
viewpage.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <style> .error{color:red} </style> </head> <body> <form:form action="helloagain" modelAttribute="emp"> Username: <form:input path="name"/> <br><br> Password(*): <form:password path="pass"/> <form:errors path="pass" cssClass="error"/><br><br> <input type="submit" value="submit"> </form:form> </body> </html>
final.jsp
<html> <body> Username: ${emp.name} <br><br> Password: ${emp.pass} </body> </html>
Output:
Inviiamo il modulo senza inserire la password.
Ora, inseriamo la password e quindi inviamo il modulo.