#NotNull, #Email annotation not working - validation

im trying some of the validation capabilities of spring MVC but i just cant make #NotNull and #Email work, #Size is working pretty well, but it seem the other 2 just doesnt report errors at the bindingresult.
could anyone give an idea.
package com.carloscortina.paidos.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.ScriptAssert;
#ScriptAssert(lang="javascript",
script="_this.confirmPassword.equals(_this.password)",
message = "personal.password.mismatch.message")
public class PersonalRegistryForm {
private Long id;
private String pNombre,sNombre,apellidoP,apellidoM,
username,password,confirmPassword,email,telCel,telefono,categoria;
boolean acceptTerms=true;
/**
* #return the id
*/
public Long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* #return the pNombre
*/
public String getpNombre() {
return pNombre;
}
/**
* #param pNombre the pNombre to set
*/
public void setpNombre(String pNombre) {
this.pNombre = pNombre;
}
/**
* #return the sNombre
*/
public String getsNombre() {
return sNombre;
}
/**
* #param sNombre the sNombre to set
*/
public void setsNombre(String sNombre) {
this.sNombre = sNombre;
}
/**
* #return the apellidoP
*/
public String getApellidoP() {
return apellidoP;
}
/**
* #param apellidoP the apellidoP to set
*/
public void setApellidoP(String apellidoP) {
this.apellidoP = apellidoP;
}
/**
* #return the apellidoM
*/
public String getApellidoM() {
return apellidoM;
}
/**
* #param apellidoM the apellidoM to set
*/
public void setApellidoM(String apellidoM) {
this.apellidoM = apellidoM;
}
/**
* #return the username
*/
#NotNull
#Size(min=4,max=12)
public String getUsername() {
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the password
*/
#NotNull
#Size(min=8,max=12)
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the confirmPassword
*/
#NotNull
public String getConfirmPassword() {
return confirmPassword;
}
/**
* #param confirmPassword the confirmPassword to set
*/
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
/**
* #return the email
*/
#NotNull
#Email
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the telCel
*/
public String getTelCel() {
return telCel;
}
/**
* #param telCel the telCel to set
*/
public void setTelCel(String telCel) {
this.telCel = telCel;
}
/**
* #return the telefono
*/
public String getTelefono() {
return telefono;
}
/**
* #param telefono the telefono to set
*/
public void setTelefono(String telefono) {
this.telefono = telefono;
}
/**
* #return the categoria
*/
public String getCategoria() {
return categoria;
}
/**
* #param categoria the categoria to set
*/
public void setCategoria(String categoria) {
this.categoria = categoria;
}
/**
* #return the acceptTerms
*/
public boolean isAcceptTerms() {
return acceptTerms;
}
/**
* #param acceptTerms the acceptTerms to set
*/
public void setAcceptTerms(boolean acceptTerms) {
this.acceptTerms = acceptTerms;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this);
builder.append("id", id);
builder.append("pNombre", pNombre);
builder.append("sNombre", sNombre);
builder.append("apellidoP", apellidoP);
builder.append("apellidoM", apellidoM);
builder.append("username", username);
builder.append("password", password);
builder.append("confirmPassword", confirmPassword);
builder.append("email", email);
builder.append("telCel", telCel);
builder.append("telefono", telefono);
builder.append("categoria", categoria);
builder.append("acceptTerms", acceptTerms);
return builder.toString();
}
}
The Controller
package com.carloscortina.paidos;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.carloscortina.paidos.model.PersonalRegistryForm;
#Controller
#RequestMapping(value="/personal")
public class PersonalController {
private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);
private final static String regForm="personal/RegistryForm";
private final static String regSubmit="redirect:RegistrySubmit";
#RequestMapping(value="new",method=RequestMethod.GET)
public String getPersonalRegistrationForm(Model model){
logger.info("desplegando forma");
PersonalRegistryForm form = new PersonalRegistryForm() ;
model.addAttribute("personalRegForm",form);
return regForm;
}
#RequestMapping(value="",method=RequestMethod.POST)
public String submitPersonalRegistrationForm(#ModelAttribute("personalRegForm") #Valid PersonalRegistryForm form,
BindingResult result){
//convertPasswordError(result);
logger.info("Errores -->"+result.toString());
return (result.hasErrors() ? regForm: regSubmit);
}
#InitBinder
public void initBinder(WebDataBinder binder){
binder.setAllowedFields(new String[]{
"username","password","confirmPassword","pNombre",
"sNombre","apellidoP","apellidoM","email","telefono",
"telCel","categoria","acceptTerms"});
}
}
The JSP
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:message var="pageTitle" code="newUserRegistration.pageTitle" />
<spring:message var="allFields" code="newUserRegistration.message.allFieldsRequired" />
<spring:message var="username" code="newUserRegistration.label.username" />
<spring:message var="password" code="newUserRegistration.label.password" />
<spring:message var="confirmPassword" code="newUserRegistration.label.confirmPassword" />
<spring:message var="email" code="newUserRegistration.label.email" />
<spring:message var="firstName" code="newUserRegistration.label.pnombre" />
<spring:message var="secondName" code="newUserRegistration.label.snombre" />
<spring:message var="lastName" code="newUserRegistration.label.apellidop" />
<spring:message var="lastName1" code="newUserRegistration.label.apellidom" />
<spring:message var="telephone" code="newUserRegistration.label.telefono" />
<spring:message var="cellphone" code="newUserRegistration.label.celular" />
<spring:message var="category" code="newUserRegistration.label.categoria" />
<spring:message var="acceptTerms" code="newUserRegistration.label.terms" />
<spring:message var="submit" code="newUserRegistration.label.registrar" />
<head>
<title>${pageTitle}</title>
</head>
<body>
<div>
<form:form action="." modelAttribute="personalRegForm">
<h1>${pageTitle}</h1>
<form:errors path="*">
<div><spring:message code="error.global" /></div>
</form:errors>
<div>
${username}
<form:input path="username"/>
<form:errors path="username">
<div><form:errors path="username" htmlEscape="false" /></div>
</form:errors>
</div>
<div>
${password}
<form:password path="password"/>
<form:errors path="password">
<div><form:errors path="password" htmlEscape="false" /></div>
</form:errors>
</div>
<div>
${confirmPassword}
<form:password path="confirmPassword"/>
</div>
<div>
${email}
<form:input path="email"/>
<form:errors>
<div><form:errors path="email" htmlEscape="false"/></div>
</form:errors>
</div>
<div>
${firstName}
<form:input path="pNombre"/>
</div>
<div>
${secondName}
<form:input path="sNombre"/>
</div>
<div>
${lastName}
<form:input path="ApellidoP"/>
</div>
<div>
${lastName1}
<form:input path="ApellidoM"/>
</div>
<div>
${telephone}
<form:input path="telefono"/>
</div>
<div>
${cellphone}
<form:input path="telCel"/>
</div>
<div>
${category}
<form:input path="categoria"/>
</div>
<div>
<form:checkbox path="acceptTerms"/>
${acceptTerms}
</div>
<div>
<input type="submit" value="${submit}"/>
</div>
</form:form>
</div>
</body>

It seem it was my misunderstanding of the terms and capabilities of the validations.
#NotNull and #Email are indeed both working but not as i imagined.
#NotNull is for validating Null not empty and that was my misunderstanding and similarly #Email cant do the validation on empty strings.
well thanks to everyone that reads this and i hope this can help someone. it might be too noob but its good to learn.

Related

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'search' available as request attribute

I'm new to Spring MVC and I have an error with a form validation and I don't know why.
This is the model:
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import org.springframework.stereotype.Component;
#Component
public class Search implements Serializable {
#Size(max = 20)
private String userInput;
#Size(max = 10)
private String ascending;
#Size(max = 10)
private String descending;
#Temporal(TemporalType.DATE)
private Date fromDate;
#Temporal(TemporalType.DATE)
private Date toDate;
#Size(max=100)
private String genres;
public String getGenres() {
return genres;
}
public void setGenres(String genres) {
this.genres = genres;
}
public String getUserInput() {
return userInput;
}
public void setUserInput(String userInput) {
this.userInput = userInput;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
}
Here is the form:
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<sf:form action="/newSearch" method="post" modelAttribute="search">
<sf:input path="userInput" type="text" class="input_style" id="userInput" />
<button class="search_button"><img class="search_icon" src="resources/img/search/search_icon.png" /></button>
<sf:select id="genres" path="genres" multiple="multiple">
</sf:select>
<sf:input id="fromDate" path="fromDate" />
<sf:input id="toDate" path="toDate" type="text" />
<sf:input id="ascending" path="ascending" type="radio" checked="checked" />
<sf:input id="descending" path="descending" type="radio" />
</sf:form>
and here is the Controller:
#RequestMapping(value = "/newSearch", method = RequestMethod.POST)
public String getSearch(#Valid Search search, BindingResult result, Model m) {
if(result.hasErrors()) {
return "home";
}
System.out.println("----------------Search--------------------");
System.out.println(search.getGenres());
System.out.println(search.getUserInput());
return "search";
}
The error is:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'search' available as request attribute
Add #ModelAttribute("search") before #Valid making the method's signature look like
public String getSearch(#ModelAttribute("search") #Valid Search search, BindingResult result, Model m)
Also try
<sf:form action="/newSearch" method="post" commandName="search">
instead of
<sf:form action="/newSearch" method="post" modelAttribute="search">

<form:checkbox> hidden value messing my form?

i have a field in a form and its bound to an user class, in the form its this field
<tr>
<td>AcceptTerms:</td>
<td><form:checkbox path="acceptTerms"/><td>
</tr>
but at the moment of submitting the form an error arises
The request sent by the client was syntactically incorrect.
i inspected it with firebug and got this
Parameters application/x-www-form-urlencoded
_acceptTerms on
email ZX
password ZXZX
rol 2
username ZxZ
Fuente
username=ZxZ&password=ZXZX&email=ZX&rol=2&_acceptTerms=on
the _acceptTerms its a hidden value for the checkbox that as i assume it a default of spring tag <form:checkbox>.
this arises 3 questions for me:
does this field (_acceptTerms) mess with my form submit?
why is _acceptTerms always set to on?
if this field does indeed mess up my form how can i get rid of it or how should i process it? add to the user model?
thanks in advance
Edit
package com.carloscortina.paidosSimple.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;
#Controller
public class PersonalController {
private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);
#Autowired
private PersonalService personalService;
#Autowired
private UsuarioService usuarioService;
#Autowired
private CategoriaService categoriaService;
#RequestMapping(value="/usuario/add")
public ModelAndView addUsuarioPage(){
ModelAndView modelAndView = new ModelAndView("add-usuario-form");
modelAndView.addObject("categorias",categorias());
modelAndView.addObject("user", new Usuario());
return modelAndView;
}
#RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
public ModelAndView addingUsuario(#ModelAttribute Usuario user){
ModelAndView modelAndView = new ModelAndView("add-personal-form");
usuarioService.addUsuario(user);
logger.info(modelAndView.toString());
String message= "Usuario Agregado Correctamente.";
modelAndView.addObject("message",message);
modelAndView.addObject("staff",new Personal());
return modelAndView;
}
#RequestMapping(value="/personal/list")
public ModelAndView listOfPersonal(){
ModelAndView modelAndView = new ModelAndView("list-of-personal");
List<Personal> staffMembers = personalService.getAllPersonal();
logger.info(staffMembers.get(0).getpNombre());
modelAndView.addObject("staffMembers",staffMembers);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
public ModelAndView editPersonalPage(#PathVariable int id){
ModelAndView modelAndView = new ModelAndView("edit-personal-form");
Personal staff = personalService.getPersonal(id);
logger.info(staff.getpNombre());
modelAndView.addObject("staff",staff);
return modelAndView;
}
#RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingPersonal(#ModelAttribute Personal staff, #PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.updatePersonal(staff);
String message = "Personal was successfully edited.";
modelAndView.addObject("message", message);
return modelAndView;
}
#RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
public ModelAndView deletePersonal(#PathVariable int id) {
ModelAndView modelAndView = new ModelAndView("home");
personalService.deletePersonal(id);
String message = "Personal was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
private Map<String,String> categorias(){
List<Categoria> lista = categoriaService.getCategorias();
Map<String,String> categorias = new HashMap<String, String>();
for (Categoria categoria : lista) {
categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
}
return categorias;
}
Form.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<head>
<title>Add personal page</title>
</head>
<body>
<p>${message}<br>
<h1>Add User Page</h1>
<p>Here you can add a new staff member.</p>
<form:form method="POST" commandName="user" action="${pageContext.request.contextPath}/usuario/add/process" >
<table>
<tbody>
<tr>
<td>Nombre de Usuario:</td>
<td><form:input path="username"/><td>
</tr>
<tr>
<td>Contraseña:</td>
<td><form:password path="password"/><td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email"/><td>
</tr>
<tr>
<td>Categoria:</td>
<td><form:select path="rol">
<form:options items="${categorias}" />
</form:select><td>
</tr>
<tr>
<td>AcceptTerms:</td>
<td><form:checkbox path="acceptTerms"/><td>
</tr>
<tr>
<td><input type="submit" value="Registrar"><td>
</tr>
</tbody>
</table>
</form:form>
<p>Home Page</p>
</body>
Log
DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/paidosSimple/usuario/add/process]
DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /usuario/add/process
DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'personalController'
DEBUG: org.springframework.beans.BeanUtils - No property editor [com.carloscortina.paidosSimple.model.CategoriaEditor] found for type com.carloscortina.paidosSimple.model.Categoria according to 'Editor' suffix convention
DEBUG: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request
Usuario.java
package com.carloscortina.paidosSimple.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Usuario")
public class Usuario {
private Integer id;
private String username,password,email;
boolean acceptTerms = false,active=true;
private Categoria rol;
/**
* #return the id
*/
#Id
#GeneratedValue
#Column(name="id")
public Integer getId() {
return id;
}
/**
* #return the rol
*/
#OneToOne(cascade=CascadeType.ALL)
#JoinTable(name="usuario_rol",
joinColumns={#JoinColumn(name="Usuario",referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="Rol",referencedColumnName="id")})
public Categoria getRol() {
return rol;
}
/**
* #param rol the rol to set
*/
public void setRol(Categoria rol) {
this.rol = rol;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the username
*/
#Column(name="Username")
public String getUsername() {
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the password
*/
#Column(name="Password")
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #return the email
*/
#Column(name="Email")
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the acceptTerms
*/
#Column(name="acceptTerms")
public boolean isAcceptTerms() {
return acceptTerms;
}
/**
* #param acceptTerms the acceptTerms to set
*/
public void setAcceptTerms(boolean acceptTerms) {
this.acceptTerms = acceptTerms;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Usuario [id=" + id + ", username=" + username + ", password="
+ password + ", email=" + email + ", acceptTerms="
+ acceptTerms + "]";
}
}
Categoria.java
package com.carloscortina.paidosSimple.model;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Categoria")
public class Categoria {
private int id;
private String categoria,descripcion;
private Set<Usuario> UserRoles;
/**
* #return the userRoles
*/
#OneToMany(cascade=CascadeType.ALL)
#JoinTable(name="usuario_rol",
joinColumns={#JoinColumn(name="Categoria",referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="Usuario",referencedColumnName="id")})
public Set<Usuario> getUserRoles() {
return UserRoles;
}
/**
* #param userRoles the userRoles to set
*/
public void setUserRoles(Set<Usuario> userRoles) {
UserRoles = userRoles;
}
/**
* #return the id
*/
#Id
#GeneratedValue
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the categoria
*/
public String getCategoria() {
return categoria;
}
/**
* #param categoria the categoria to set
*/
public void setCategoria(String categoria) {
this.categoria = categoria;
}
/**
* #return the descripcion
*/
public String getDescripcion() {
return descripcion;
}
/**
* #param descripcion the descripcion to set
*/
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
Have you checked if your form submission works if you remove form:checbox, to ensure that indeed this checkbox is causing the issue
can you share debug logs of server
Also share your controller method that is hadnling this form submission including #requestMapping value
you can add a custom binder to convert rol into category
Create a custom property editor
public class CategoryEditor extends PropertyEditorSupport {
#Override
public void setAsText(String text) {
Category cat = new Category ();
//set rol vlaue in cat
setValue(cat);
}
now use following method in your controller
#InitBinder
public void initBinderAll(WebDataBinder binder) {
binder.registerCustomEditor(Category .class, new CategoryEditor ()); }

How to implement validations using annotations in struts2 in action that implements ModelDriven interface?

I am trying to implement validation using annotations, but these validations don't work and the form gets submitted with null values.
I don't know what is missing, how to implement validations using annotations in struts2 in action that implements ModelDriven interface?
This is my struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="saveOrUpdateUser" method="saveOrUpdate1" class="com.vaannila.web.Userqqqq">
<result name="success" type="redirect">listUser</result>
<result name="input">/register.jsp</result>
</action>
<action name="listUser" method="list" class="com.vaannila.web.Userqqqq">
<result name="success">/register.jsp</result>
<result name="input">/register.jsp</result>
</action>
<action name="editUser" method="edit" class="com.vaannila.web.Userqqqq">
<result name="success">/register.jsp</result>
<result name="input">/register.jsp</result>
</action>
<action name="deleteUser" method="delete" class="com.vaannila.web.Userqqqq">
<result name="success" type="redirect">listUser</result>
<result name="input">/register.jsp</result>
</action>
</package>
</struts>
This is my jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:actionerror/>
<s:form action="saveOrUpdateUser" validate="true">
<s:push value="user">
<s:hidden name="id" />
<s:textfield name="name" label="User Name" required="true"/>
<s:radio name="gender" label="Gender" list="{'Male','Female'}" />
<s:select name="country" list="{'India','USA','UK'}" headerKey=""
headerValue="Select" label="Select a country" />
<s:textarea name="aboutYou" label="About You" />
<s:checkbox name="mailingList"
label="Would you like to join our mailing list?" />
<s:submit />
</s:push>
</s:form>
<s:if test="userList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="name" /></td>
<td><s:property value="gender" /></td>
<td><s:property value="country" /></td>
<td><s:property value="aboutYou" /></td>
<td><s:property value="mailingList" /></td>
<td><s:url id="editURL" action="editUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
This is my action class
package com.vaannila.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.vaannila.dao.UserDAO;
import com.vaannila.domain.User;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = -6659925652584240539L;
private User user = new User();
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAO();
#Override
public User getModel() {
return user;
}
/**
* To save or update user.
* #return String
*/
public String saveOrUpdate()
{
System.out.println(user.getName());
userDAO.saveOrUpdateUser(user);
return SUCCESS;
}
/**
* To list all users.
* #return String
*/
public String list()
{
userList = userDAO.listUser();
return SUCCESS;
}
/**
* To delete a user.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
userDAO.deleteUser(Long.parseLong(request.getParameter("id")));
return SUCCESS;
}
/**
* To list a single user by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong(request.getParameter("id")));
return SUCCESS;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
This is my BEAN
package com.vaannila.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
#Entity
#Table(name="USER1")
public class User {
private Long id;
private String name;
private String gender;
private String country;
private String aboutYou;
private Boolean mailingList;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "name", message = "User Name field is empty.")
#Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "gender", message = "gender field is empty.")
#Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
#Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
You need to add #VisitorFieldValidator annotation to user getter inside your action class.
#VisitorFieldValidator(appendPrefix = false)
public User getUser() {
return user;
}
Note that you need to set appendPrefix to false if your are using field names without user. prefix in JSP.
Also, you are probably want #RequiredStringValidator not #RequiredFieldValidator inside your bean.
#RequiredStringValidator(message = "User Name field is empty.")
#Column(name="USER_NAME")
public String getName() {
return name;
}

Cross field bean validation - why you no work

I've got a little problem here with my application. I'd like to check if fields password and confirm password match together, so I tried to do it like in the first answer for this question: Cross field validation with Hibernate Validator (JSR 303)
The problem is that it actually doesn't work and I HAVE NO IDEA WHY. Please, help me! This is my first post here, so please don't be too harsh for me.
Here's my Annotation :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints;
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
*
* #author lukasz
*/
#Documented
#Constraint(validatedBy = FieldMatchValidator.class)
#Target({ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface FieldMatch {
String message() default "{pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints.FieldMatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String first();
String second();
}
Here's my ValidatorClass:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.beanutils.BeanUtils;
/**
*
* #author lukasz
*/
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {
private String firstFieldName;
private String secondFieldName;
#Override
public void initialize(FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
try {
String sFirstField = BeanUtils.getProperty(value, firstFieldName);
String sSecondField = BeanUtils.getProperty(value, secondFieldName);
if(sFirstField.equals(sSecondField)){
return true;
}
} catch (IllegalAccessException ex) {
Logger.getLogger(FieldMatchValidator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(FieldMatchValidator.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchMethodException ex) {
Logger.getLogger(FieldMatchValidator.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
}
And here's my bean:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.lodz.p.zsk.ssbd2012.ssbd12.Beans;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints.CheckEmail;
import pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints.FieldMatch;
import pl.lodz.p.zsk.ssbd2012.ssbd12.entities.Account;
import pl.lodz.p.zsk.ssbd2012.ssbd12.mok.endpoint.MokEndpointLocal;
/**
*
* #author krzys
* #author lukasz
*/
#ManagedBean
#RequestScoped
#FieldMatch(first = "password", second = "password2", message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.ValidationConstraints.FieldMatch}")
public class RegisterBean {
/**
* Creates a new instance of RegisterBean
*/
#EJB
MokEndpointLocal endpoint;
#Size(min = 3, max = 16, message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.login.size}")
#Pattern(regexp = "[a-zA-Z0-9]+", message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.login.invalid}")
private String login;
#Size(min = 6, max = 64, message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.password.size}")
#Pattern(regexp = "[a-zA-Z0-9]+", message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.password.invalid}")
private String password;
private String password2;
#Pattern(regexp = "[A-Ż][a-ż]+", message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.name.invalid}")
private String name;
#Pattern(regexp = "[A-Ż][a-ż]+", message = "{pl.lodz.p.zsk.ssbd2012.ssbd12.Beans.RegisterBean.surname.invalid}")
private String surname;
#CheckEmail
private String email = "";
/**
* #return the login
*/
public String getLogin() {
return login;
}
/**
* #param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String register ()
{
// Account account = new Account();
// account.setLogin(login);
// account.setHaslo(password);
// account.setImie(name);
// account.setNazwisko(surname);
// account.setEmail(email);
// endpoint.register(account);
return "registerSucces";
}
/**
* #return the surname
*/
public String getSurname() {
return surname;
}
/**
* #param surname the surname to set
*/
public void setSurname(String surname) {
this.surname = surname;
}
}
And here's JSF:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<h:outputStylesheet name="menu.css" library="css" />
<title>#{messages.registration}</title>
</h:head>
<h:body>
<ui:composition template="./../resources/mainTemplate.xhtml">
<h4>#{messages.registration}</h4>
<ui:define name="content">
<h4>#{messages.registration}</h4>
<h1>#{messages.registrationInfo1}</h1>
#{messages.registrationInfo2}
<h:form>
<h2>
<h:outputText value="#{messages.loginForm}"/>
<h:inputText id="login" value="#{registerBean.login}" />
</h2>
<h2>
<h:outputText value="#{messages.passwordForm}" />
<h:inputSecret id="password" value="#{registerBean.password}" />
</h2>
<h2>
<h:outputText value="#{messages.repeatPasswordForm}"/>
<h:inputSecret id="confirm" value="#{registerBean.password2}" />
</h2>
<h2>
<h:outputText value="#{messages.nameForm}"/>
<h:inputText id="name" value="#{registerBean.name}" />
</h2>
<h2>
<h:outputText value="#{messages.surnameForm}"/>
<h:inputText id="surname" value="#{registerBean.surname}" />
</h2>
<h2>
<h:outputText value="#{messages.emailForm}"/>
<h:inputText id="email" value="#{registerBean.email}" />
</h2>
<h2>
<h:commandButton value="#{messages.send}" action="#{registerBean.register()}" />
</h2>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
Class-level constraints are not triggered automatically by JSF during validation phase. You can use only field-level constraints (moreover not all fields are valuated by JSF but only those that are in your facelet).
If you want to use bean validation you can perform validation manually:
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Test>> violations = validator.validate( this, Default.class );
You can do it in registration method of your bean or after update model phase (but I've never tried it).
Anyway you can use JSF validation instead of bean validation or check the passwords directly in the registration method:
public String registration() {
...
if ( !password.equals(password2) ) {
FacesContext.getCurrentInstance().addMessage( null, new FacesMessage( "Passwords do not match" ) );
return null;
}
...
}

Spring MVC: Form Not Submitting

In my Spring MVC application, the Form Controller is correctly wired and displays the form as intended.
But the Submit button does not work. Moreover, the onSubmit() method of the FormController never gets invoked, because my debug print statements are not shown.
Instead, when I click Submit, the form re-loads and some of the fields get changed (very strange behavior).
I implemented my FormController as usual in Spring MVC:
public class RegisterController extends SimpleFormController {
public RegisterController()
{
setCommandClass(Customer.class);
setCommandName("customer");
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
// never gets run!
Customer customer = (Customer) command;
System.out.println("TEST. Obtained Customer object: " + customer.toString());
}
}
My bean wiring for the Dispatcher Servlet is:
<bean name="/register.htm" class="techbooks.web.RegisterController"
p:formView="register" p:successView="home"/>
"register" refers to register.htm(.jsp) and "home" to home.htm(.jsp), both of which exist.
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Language" content="en-us" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TechBooks.com</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<body>
<center>
<table style="width: 850px" class="style2">
<form:form method="POST" commandName="customer">
<tr>
<td><h1>Register New Customer</h1></td>
</tr>
<tr>
<td>
<table>
<tr>
<td align="left">Customer ID:</td>
<td align="left"><form:input path="customerId"/></td>
</tr>
<tr>
<td align="left">Customer Password:</td>
<td align="left"><form:password path="customerPassword"/></td>
</tr>
<tr>
<td align="left">Customer First Name:</td>
<td align="left"><form:input path="customerFirstName"/></td>
</tr>
<tr>
<td align="left">Customer Last Name:</td>
<td align="left"><form:input path="customerLastName"/></td>
</tr>
<tr>
<td align="left">Customer Address:</td>
<td align="left"><form:input path="customerAddress"/></td>
</tr>
<tr>
<td align="left">Customer City:</td>
<td align="left"><form:input path="customerCity"/></td>
</tr>
<tr>
<td align="left">Customer State:</td>
<td align="left"><form:input path="customerState"/></td>
</tr>
<tr>
<td align="left">Customer Zip Code:</td>
<td align="left"><form:input path="customerZipCode"/></td>
</tr>
<tr>
<td align="left">Customer Email Address:</td>
<td align="left"><form:input path="customerEmailAddress"/></td>
</tr>
<tr>
<td align="left">Date Added:</td>
<td align="left"><form:input path="customerDateAdded" /></td>
</tr>
<tr>
<td align="left">Is Admin?</td>
<td align="left"><form:checkbox path="customerIsAdmin"/></td>
</tr>
<tr>
<td align="left"><input type="submit" value="Register"/><br/><input type="button" value="Cancel"/>
</td>
<td align="left"> </td>
</tr>
</table>
</td>
</tr>
</form:form>
</table>
</center>
</body>
</html>
Customer bean class:
package techbooks.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Customer implements Serializable {
#Id
private String customerId;
private String customerPassword;
private String customerFirstName;
private String customerLastName;
private String customerAddress;
private String customerCity;
private String customerState;
private String customerZipCode;
private String customerEmailAddress;
private Date customerDateAdded;
private Boolean customerIsAdmin;
/**
* #return the customerId
*/
public String getCustomerId() {
return customerId;
}
/**
* #param customerId the customerId to set
*/
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
/**
* #return the customerPassword
*/
public String getCustomerPassword() {
return customerPassword;
}
/**
* #param customerPassword the customerPassword to set
*/
public void setCustomerPassword(String customerPassword) {
this.customerPassword = customerPassword;
}
/**
* #return the customerFirstName
*/
public String getCustomerFirstName() {
return customerFirstName;
}
/**
* #param customerFirstName the customerFirstName to set
*/
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
/**
* #return the customerLastName
*/
public String getCustomerLastName() {
return customerLastName;
}
/**
* #param customerLastName the customerLastName to set
*/
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
/**
* #return the customerAddress
*/
public String getCustomerAddress() {
return customerAddress;
}
/**
* #param customerAddress the customerAddress to set
*/
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
/**
* #return the customerCity
*/
public String getCustomerCity() {
return customerCity;
}
/**
* #param customerCity the customerCity to set
*/
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
/**
* #return the customerState
*/
public String getCustomerState() {
return customerState;
}
/**
* #param customerState the customerState to set
*/
public void setCustomerState(String customerState) {
this.customerState = customerState;
}
/**
* #return the customerZipCode
*/
public String getCustomerZipCode() {
return customerZipCode;
}
/**
* #param customerZipCode the customerZipCode to set
*/
public void setCustomerZipCode(String customerZipCode) {
this.customerZipCode = customerZipCode;
}
/**
* #return the customerEmailAddress
*/
public String getCustomerEmailAddress() {
return customerEmailAddress;
}
/**
* #param customerEmailAddress the customerEmailAddress to set
*/
public void setCustomerEmailAddress(String customerEmailAddress) {
this.customerEmailAddress = customerEmailAddress;
}
/**
* #return the customerDateAdded
*/
public Date getCustomerDateAdded() {
return customerDateAdded;
}
/**
* #param customerDateAdded the customerDateAdded to set
*/
public void setCustomerDateAdded(Date customerDateAdded) {
this.customerDateAdded = customerDateAdded;
}
/**
* #return the customerIsAdmin
*/
public Boolean getCustomerIsAdmin() {
return customerIsAdmin;
}
/**
* #param customerIsAdmin the customerIsAdmin to set
*/
public void setCustomerIsAdmin(Boolean customerIsAdmin) {
this.customerIsAdmin = customerIsAdmin;
}
}
As I said, the form never gets submitted, and the onSubmit() of the Controller never executes. Thanks for any ideas
I think there may be some binding errors so I suggest to override
protected ModelAndView processFormSubmission(HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors)
throws Exception
and check that errors.hasErrors() returns false, just to be sure that the submission was successful.
See processFormSubmission
Further to above accepted answer I would like to point out a few thing -
If you have overridden
protected Map referenceData(HttpServletRequest request, Object command, Errors errors)
method in your controller which is typically invoked on a GET request will be called even when the form is submitted (POST). This is because if there are any Binding error form will be reloaded calling referecenData() again. Ofcourse you can override processFormSubmission() method but if you are just interested in overriding onSubmit() method I suggest override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors)
method and see the BindException error.

Resources