Spring MVC: Form Not Submitting - model-view-controller

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.

Related

not-null property references a null value while adding new user with foreign key

I'm trying to insert a new user to the database , which contains a foreign key to userRole . i populated a roles dropdown list in jsp from the database , inserted in a form in which I'll add a new user . i'm really blocked for days now ... user also has a primary key.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: jpa.project.model.DemUser.idRole
Role entity :
#Entity
#Table(name="DEM_ROLE")
#NamedQuery(name="DemRole.findAll", query="SELECT d FROM DemRole d")
public class DemRole implements Serializable {
private static final long serialVersionUID = 1L;
private long idRole;
private String libRole;
private String librole;
public DemRole() {
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID_ROLE", unique=true, nullable=false)
public long getIdRole() {
return this.idRole;
}
public void setIdRole(long idRole) {
this.idRole = idRole;
}
#Column(name="LIB_ROLE", nullable=false, length=50)
public String getLibRole() {
return this.libRole;
}
public void setLibRole(String libRole) {
this.libRole = libRole;
}
#Column(length=255)
public String getLibrole() {
return this.librole;
}
public void setLibrole(String librole) {
this.librole = librole;
}
}
User Entity :
#Entity
#Table(name="DEM_USER")
#NamedQuery(name="DemUser.findAll", query="SELECT d FROM DemUser d")
public class DemUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID_USER", unique=true, nullable=false)
private long idUser;
#Column(name="NAME_USER", nullable=false, length=50)
private String nameUser;
#Column(nullable=false, length=20)
private String password;
//uni-directional many-to-one association to DemRole
#ManyToOne(cascade={CascadeType.ALL},fetch = FetchType.LAZY)
#JoinColumn(name="ID_ROLE", nullable=false)
private DemRole idRole;
public DemUser() {
}
public long getIdUser() {
return this.idUser;
}
public void setIdUser(long idUser) {
this.idUser = idUser;
}
public String getNameUser() {
return this.nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public DemRole getIdRole() {
return this.idRole;
}
public void setIdRole(DemRole idRole) {
this.idRole = idRole;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
Controller :
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView home(ModelAndView model,HttpServletRequest request) throws IOException {
List<DemUser> listUsers = service.getAllUsers();
model.addObject("listUsers", listUsers);
List<DemRole> listRoles = service.getRoles();
request.setAttribute("listRoles", listRoles);
/*List<DemRole> listRoles = service.getRoles();
model.addObject("listRoles", listRoles); */
DemUser user = new DemUser();
model.addObject("DemUser", user);
model.setViewName("manageusers");
return model;
}
#RequestMapping(value = "/actionadduser", method = RequestMethod.POST)
public String actionadduser(ModelAndView model,#ModelAttribute DemRole role ,#ModelAttribute DemUser user,BindingResult result) {
service.addUser(user);
return "redirect:/";
}
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="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="left">
This is manage users
<table border="1">
<h1>users</h1>
<tr><td> Names : </td> </tr>
<c:forEach var="user" items="${listUsers}">
<tr>
<td>${user.nameUser}</td>
</tr>
</c:forEach>
</table>
</div>
<div align="right">
<h1>New user</h1>
<form:form action="actionadduser" method="post" modelAttribute="DemUser">
<table>
<form:hidden path="idUser" />
<form:hidden path="password" value="password" />
<tr>
<td>Name:</td>
<td><form:input path="nameUser" /></td>
</tr>
<tr>
<td>Roles :</td>
<td>
<form:select path="idRole">
<form:options items="${listRoles}" itemValue="idRole" itemLabel="libRole"></form:options>
</form:select></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
There are couple of points,
As roles already exist before adding a new User, So you don't need to have any type of cascading in #ManyToOne mapping, you can remove cascading at all.
//uni-directional many-to-one association to DemRole
#ManyToOne
#JoinColumn(name="ID_ROLE", nullable=false)
private DemRole idRole;
I can see in your POST method, you are receiving DemRole and DemUser and calling the service class to persist the user, but I can't see anywhere that you are populating the received role object into received user object. As User is having Role object, so before saving user object, you need to have something like this,
#RequestMapping(value = "/actionadduser", method = RequestMethod.POST)
public String actionadduser(ModelAndView model,#ModelAttribute DemRole role ,#ModelAttribute DemUser user,BindingResult result) {
// set role object to user object
user.setIdRole(role); // setter for DemRole object.
service.addUser(user);
return "redirect:/";
}
Hope this helps, please let me know if any more clarifications are needed.

Binding form parameters from JSP to spring controller

I know this is a question which has been asked before. I did look at those questions but I was still not able to resolve my problem and thus writing in on stackoverflow. I am trying to bind the form parameters from my form addArticles.jsp to the controller. On the controller when I do a system.out.println I only get the categoryId and do not get the categoryName. I am not sure what I am doing is incorrect and pretty amused.
addArticles.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Article</title>
</head>
<body>
<center>
<h2>Create New Article</h2>
<form:form action="/one2one/articles/save.do" method="POST" modelAttribute="command">
<table>
<tr>
<td><form:label path="id">Article ID</form:label></td>
<td><form:input path="id" value="${article.id}"></form:input></td>
</tr>
<tr>
<td><form:label path="title">Article Title</form:label></td>
<td><form:input path="title" value="${article.title}"></form:input></td>
</tr>
<tr>
<td><form:label path="description">Article Description:</form:label></td>
<td><form:input path="description" value="${article.description}" cssStyle="width: 150px;"></form:input></td>
</tr>
<tr>
<td><form:label path="category.categoryId">Category Type</form:label></td>
<td><form:select path="category.categoryId" cssStyle="width: 150px;">
<option value="-1">Select a type</option>
<c:forEach items="${categories}" var="category">
<option <c:if test="${category.categoryName eq article.category.categoryName}">selected="selected"</c:if>
value="${category.categoryId}">${category.categoryName}</option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="keywords">Article Keywords:</form:label></td>
<td><form:input path="keywords" value="${article.keywords}"></form:input></td>
</tr>
<tr>
<td><form:label path="content">Article Content:</form:label></td>
<td><form:input path="content" value="${article.content}"></form:input></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="SAVE"/></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
ArticlesController.java
package com.java.bricks.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.java.bricks.model.Article;
import com.java.bricks.model.Category;
import com.java.bricks.service.ArticleService;
import com.java.bricks.service.CategoryService;
#Controller("articlesController")
#RequestMapping(value="/articles")
public class ArticlesController {
#Autowired
private ArticleService articleService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value="/list", method=RequestMethod.GET)
public ModelAndView listArticles(#ModelAttribute("command") Article article, BindingResult bindingResult){
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
return new ModelAndView("articlesList",model);
}
#RequestMapping(value="/add",method=RequestMethod.GET)
public ModelAndView addArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
model.put("categories", categoryService.listCategories());
return new ModelAndView("addArticle",model);
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView saveArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
System.out.println("----------------------");
System.out.println(article.getCategory());
System.out.println(article.getCategory().getCategoryName());
System.out.println(article.getCategory().getCategoryId());
articleService.addArticle(article);
model.put("articles",articleService.listArticles());
return new ModelAndView("addArticle",model);
}
}
when I click save the first 4 lines of the SOP statements are
System.out.println(article.getCategory());
output: Category [categoryId=29, categoryName=null]
System.out.println(article.getCategory().getCategoryName());
null
System.out.println(article.getCategory().getCategoryId())
29
I am not sure why the categoryName is not populated in the controller.
Article.java
package com.java.bricks.model;
public class Article {
private Long id;
private String title;
private String description;
private String keywords;
private String content;
private Category category;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
You aren't going to get the category name in the form's content because the category's name is being used a the label for the option. Only the value gets bound. This is your binding path="category.categoryId". You aren't binding anything to path="category.categoryName" so it's going to be null.
So in your controller you have to get the category by its ID. If you want to do some automatic custom conversion, that is a separate question.
Here's a nice article on entity conversion.

Using object in JSP with Spring 4.0.7

I'm trying to send object in a SpringController to the client. But it doesn't work.
I've read the same questions a bunch of times, but couldn't figure it out.
Here is my code :
#Controller
#RequestMapping(value = "/departs/{from}")
public class NextTrainController {
/** Handle nextTrains request with a destination specified */
#RequestMapping(value = "/{to}", method = RequestMethod.GET)
public String getNextTrainsToDestination(#PathVariable String from, #PathVariable String to,
#RequestParam(value = "date", required = false) Date date, Model model) {
// Date null means we leave now
if (date == null)
date = new Date();
/* debug */
List<TransilienTrain> trains = new ArrayList<TransilienTrain>(5);
TransilienTrain train = new TransilienTrain();
train.setMission("VIK30");
trains.add(train);
train = new TransilienTrain();
train.setMission("KOOPA34");
trains.add(train);
train = new TransilienTrain();
train.setMission("BOUGA90");
trains.add(train);
model.addAttribute("origin", from);
model.addAttribute("destination", to);
model.addAttribute("trains", trains);
return "departs";
}
My departs.jsp :
<c:if test="${not empty trains}">
<table class="table table-striped table-hover">
<thead>
<tr>
<th class="col-sm-1">Départ</th>
<th class="col-sm-1">Train</th>
<th class="col-sm-2">Destination</th>
</tr>
</thead>
<tbody>
<c:forEach var="o" items="${trains}">
<tr>
<td>12h38*</td>
<td>${o.mission}</td>
<td>Paris Nord</td>
</tr>
</c:forEach>
</tbody>
</table>
<p>* Horraires théoriques</p>
</c:if>
My TransilienTrain class has a getter/setter for the mission attribute.
#Entity
#Table
public class TransilienTrain {
private String mission;
public String getMission() {
return mission;
}
public void setMission(String mission) {
this.mission = mission;
}
}
When I check the source code of the page, I do have the items in my list, but the o.mission isn't replaced with anything.
Found the solution. Thanks to #singh101.
Forgot to import the taglib definition:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Spring and Hibernate form binding

Ok I am having an issue and have been stuck for a few hours. I am running the current version of spring with Hibernate and need to take data from a form and save it do the database, that's all but it is giving me tons of trouble and have no idea how to go about it. Below is the controller, JSP, Model, and Dao.
Controller
private final String addNewView = "addAward";
#RequestMapping(value = "/addAwardType", method = RequestMethod.GET)
public String addAwardType() {
LOG.debug("Display form to add a new contact.");
return addNewView;
}
#RequestMapping(value = "/addAwardType", method = RequestMethod.POST)
public ModelAndView addAwardType(
#ModelAttribute("AwardTypeModel") AwardType awardType,
BindingResult result) {
return new ModelAndView(addNewView, "AwardType", new AwardTypeModel(awardType));
}
}
JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Add AwardType</h2>
<form:form method="POST" commandName="addAwardType">
<table>
<tr>
<td><form:label path="AwardType.name">Award Name</form:label></td>
<td><form:input path="AwardType.name" /></td>
</tr>
<tr>
<td><form:label path="AwardType.description">Last Name</form:label></td>
<td><form:input path="AwardType.description" /></td>
</tr>
<tr>
<td> <form:checkbox path="AwardType.isActive" value="Active"/></td>
</tr>
<tr>
<td><form:label path="AwardType.created"></form:label></td>
<td><form:input path="AwardType.created" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Award"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Model
public class AwardTypeModel extends BaseModel {
private int id;
private String name;
private String description;
private boolean active;
private Date created;
private Date modified;
/**
* Construct from persistence object
* A similar constructor will be needed in each model
* #param dbo - the Persistence Object (data base object)
*/
public AwardTypeModel(AwardType dbo){
this.id = dbo.getAwardTypeId();
this.name = dbo.getAwardName();
this.description = dbo.getDescription();
this.active = dbo.isActive();
this.created = dbo.getCreated();
this.modified = dbo.getModified();
}
/* (non-Javadoc)
* #see com.eaglecrk.recognition.model.BaseModel#convertToDb()
*/
#Override
public BasePersistence convertToDb() {
AwardType dbo = new AwardType();
dbo.setAwardTypeId(this.id);
dbo.setAwardName(this.name);
dbo.setDescription(this.description);
dbo.setActive(this.active);
dbo.setCreated(this.created);
dbo.setModified(this.modified);
return dbo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
}

#NotNull, #Email annotation not working

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.

Resources