Reputation: 85
I am new to spring framework. Currently, I am doing spring validations using annotations.
So look at my DAO Class:
public class Spitter {
private Long id;
@NotNull(message = "Username cannot be null")
@Size(min = 10, max = 14, message = "Username must be between 10 and 14 characters long")
private String username;
SETTERS AND GETTERS }
This is my controller:
@Controller
@RequestMapping("/spitters")
public class SpitterController {
@RequestMapping(value = "/edit", method=RequestMethod.GET)
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
@RequestMapping(value = "/edit/createAccount", method = RequestMethod.POST)
public String addSpitterFromForm(Model model, @Valid @ModelAttribute("spitter")Spitter spitter, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "spitters/edit";
} else {
// spitterService.addSpitter(spitter);
return "redirect:/home";
}
}
}
And JSP file:
<%--suppress XmlDuplicatedId --%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Spitter</title>
</head>
<body>
<h2>Create free Spitter account</h2>
<sf:form action="/spitters/edit/createAccount"
method="post" commandName="spitter">
<table class="formtable">
<tr>
<td class="label">User Name</td>
<td><sf:input class="control" name="username" path="username"
type="text"></sf:input></br>
<sf:errors path="username"></sf:errors></td>
</tr>
<td class="label"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</sf:form>
</body>
</html>
However, Spitter Controller can receive data from jsp form. But constraints(@NotNull and @Size) added in DAO Class don't work and I don't know why.
Upvotes: 1
Views: 772
Reputation: 221
Please be more spceific about the non-working constraints. An example would help
Maybe your bean data is valid and username is just empty string. I think you use Hibernate Validator, if so try to add @NotEmpty constraint to username field
Upvotes: 1
Reputation: 24591
I believe you need to register bean MethodValidationPostProcessor
. See Spring Docs
Upvotes: 0