Witam,, serdecznie,
przerabiam właśnie validatory w springu mvc i mam problem z działaniem takowego - w form przechodzi nawet jeśli lastName który wysyłany jest nullem. Może brakuje mi cos w mavenie, może jakaś literówka. Proszę o pomoc. Zamieszczam kod:
Maven:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
</dependencies>
Customer:
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Customer {
private String firstName;
@NotNull
@Size(min = 1, message = "is required")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Controller:
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;
import javax.validation.Valid;
@Controller
@RequestMapping("/customer")
public class CustomerController {
@RequestMapping("/showform")
public String showForm(Model model){
model.addAttribute("customer", new Customer());
return "customer-form";
}
@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("customer") Customer customer, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "customer-form";
}else{
return "customer-comf";}
}
}
.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Formularz klienta</title>
<style>
.error {
color: red
}
</style>
</head>
<body>
Wypełnij forumlarz zgłoszeniowy (* pola są wymagane)
<br><br/>
<form:form action="processForm" modelAttribute="customer">
Imię: <form:input path="firstName"></form:input>
<br><br/>
Nazwisko (*)<form:input path="lastName"></form:input>
<form:errors path="lastName" cssClass="error"></form:errors>
<br><br/>
<input type="submit" value="Wyślij zgłoszenie">
</form:form>
</body>
</html>