Olá pessoal estou fazendo alguns testes com o Spring MVC 3, seguindo o pdf da documentação, e não esta funcionando a validação:
//JSP
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<html>
<head>
<title>forms | mvc-showcase</title>
</head>
<body>
<form:form modelAttribute="user">
<form:errors path="*" cssClass="errorBox" />
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>
</body>
</html>
//Classe de Validação
package br.com.pedrosa.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import br.com.pedrosa.form.User;
public class UserValidator implements Validator {
public boolean supports(Class candidate) {
return User.class.isAssignableFrom(candidate);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName","required", "Field is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName","required", "Field is required.");
}
}
//Chamada ao formulario
package br.com.pedrosa;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import br.com.pedrosa.form.User;
@Controller
public class OlaMundoController {
@RequestMapping("/ola")
public ModelAndView ola( @ModelAttribute("user") User user) {
String mensagem = "Conhecendo o Spring MVC 3.0";
ModelAndView modelAndView = new ModelAndView("user");
modelAndView.addObject("mensagem", mensagem);
return modelAndView;
}
}
O que mais preciso ajustar?
Estou tentando agora validação via anotação e ainda não funciona:
Controller
package br.com.pedrosa;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import br.com.pedrosa.form.User;
@Controller
@RequestMapping(value="/user")
public class UserController {
private Map<Long, User> users = new ConcurrentHashMap<Long, User>();
@RequestMapping(method=RequestMethod.GET)
public String getCreateUser(Model model) {
model.addAttribute(new User());
return "user/createUser";
}
@RequestMapping(method=RequestMethod.POST)
public String create(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
return "user/createUser";
}
this.users.put(user.assignId(), user);
return "redirect:/user/" + user.getId();
}
@RequestMapping(value="{id}", method=RequestMethod.GET)
public String getView(@PathVariable Long id, Model model) {
User user = this.users.get(id);
if (user == null) {
throw new ResourceNotFoundException(id);
}
model.addAttribute(user);
return "user/view";
}
}
JSP
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<html>
<head>
<title>forms | mvc-showcase</title>
</head>
<body>
<form:form modelAttribute="user" action="user" method="post">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Ok" />
</td>
</tr>
</table>
</form:form>
</body>
</html>
Bean com validação via anotação
package br.com.pedrosa.form;
import java.util.concurrent.atomic.AtomicLong;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotNull
@Size(min=5, max=50)
private String firstName;
@NotNull
@Size(min=5, max=50)
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;
}
public Long assignId() {
this.id = idSequence.incrementAndGet();
return id;
}
private static final AtomicLong idSequence = new AtomicLong();
}
Onde estou comendo bola?
No metodo create estou usando @Valid , preciso configurar mais em algum lugar do spring para habilitar essa validação?
Ninguém esta usando o Spring MVC 3 aqui?
Kura
Outubro 23, 2012, 6:11am
#4
Cara… sei que faz tempo, mas eu estou mexendo nisso agora e tentando aprender um pouco.
Com certeza você já resolveu huahuahauh
Mas enfim… vc não tinha que por o @Validated na classe e usar o @Length ?
fala Pedrosa blz?
Também estou usando Spring MVC estou quebrando a cabeça pra fazer o redirecionamento do meu Controller para a minha jsp…
tem alguma dica?
Valeu!
[]'s