Spring MVC validations Not working - java

I am a newbie in spring validations.I have a loginform.html with 4 text fields and i was trying to validate them but the validations are not working in my form.
But it accepts each and every value i entered.
For example : If i enter an improper email it should throw me an validation error like "Enter proper Email ID"
loginform.java
public class loginform {
#NotEmpty
private String user;
#NotEmpty
#Email
private String email;
#NotEmpty(message = "Phone should not be blank.")
#Size(min = 10,max = 10)
private String phone;
#NotEmpty(message = "Enter your blog URL")
#URL
private String blog;
// Get and set methods}
login.html
<form:form action="login.html" commandName="userDetails">
<table>
<tr>
<td><font face="verdana" size="2px">User</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="user" /> <form:errors path="user"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Email</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="email" /> <form:errors path="email"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Phone</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="phone" /> <form:errors path="phone"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Blog</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="blog" /> <form:errors path="blog"></form:errors>
</font>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
ContactController.java
#Controller
public class ContactController {
#RequestMapping(value = "/get", method = RequestMethod.GET)
public String get(ModelMap model) {
loginform ud = new loginform();
ud.setUser("prem");
ud.setEmail("#gmail.com");
model.addAttribute("userDetails",ud);
return "login";
}
#RequestMapping("/login")
public String loginCheck(#Valid loginform userDetails, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "login";
} else {
model.addAttribute("lfobj", userDetails);
return "success";
}
}
spring-servlet.xml
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.spring3.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="props" />
</bean>
success.html
<body>
<font face="verdana" size="2">Welcome Mr. <b>${lfobj.user}</b>,<br>
Validations Success..!<br><br>
<u>You Entered</u><br>
</font>
<table>
<tr><td>Email</td><td>${lfobj.email}</td></tr>
<tr><td>Phone</td><td>${lfobj.phone}</td></tr>
<tr><td>Website</td><td>${lfobj.blog}</td></tr>
</table>
</body>
props.properties
NotEmpty.userDetails.user = User Name is required
NotEmpty.userDetails.email = Email is required
Email.userDetails.email = Enter valid email Id
URL.userDetails.email = Enter valid URL
OUTPUT : While running :(loginform.html - getting inputs)
*User : sriprem
Email : sri
Phone : 1323sri
Blog : nice*
It has show me the eror from my "props.properties" file but it doesnt show just directly gets all my input !!
Success.html
Welcome Mr. sriprem,
Validations Success..!
You Entered
Email prem
Phone 1234sri
Website nice
In above scenario everything was in wrong format yet it accepts the data ! Can anyone tell me what was wrong in my validations.

Follow the spring documentation:
http://docs.spring.io/spring/docs/3.0.0.RC3/reference/html/ch05s07.html
Have you configure Bean Validation Implementation? Take a look to the point 5.7.3 Configuring a DataBinder

Related

Spring 4 response to form submission dosent go thru view resolver. Gives back return string in response

I inherited a spring 4 web project at work which is configured with Tiles view framework, Spring framework for dispatcher servlet and IOC.
I am trying to build a reset password functionality which has three screens with three forms.
1)reset form. Takes the user's email and controller method sends an email with a temp password.
<form:form class="form-horizontal" action="/NCHP/reset.htm" method="post" id="resetForm">
<fieldset>
<legend>Enter your registered email address</legend>
<div class="form-group">
<div class="col-sm-12">
<input id="resetEmail" name="email" class="form-control" placeholder="Email" required="required" tabindex="1" type="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-12 ">
<span class="pull-right">
<button type="reset" class="btn btn-default" data-dismiss="modal">Back</button>
<button type="submit" class="btn btn-primary" >Submit</button>
</span>
</div>
</div>
</fieldset>
</form:form>
2) Form to enter temp pwd:
<form:form class="form-horizontal" name="verify" method="POST" id='verifyform'>
<div class="form-group has-feedback">
<i class="glyphicon glyphicon-user form-control-feedback"></i>
<input type="text" id="inputEmailVerify" name="userNameVerify" placeholder="User Name" class="form-control" autofocus="autofocus">
</div>
<div class="form-group has-feedback">
<i class="glyphicon glyphicon-lock form-control-feedback"></i>
<input type="password" name="passwordVerify" id="inputPasswordVerify" placeholder="Password" class="form-control" autofocus="autofocus">
</div>
<div class="form-group" id="verify-btn">
<div class="col-sm-12 ">
<span class="pull-right">
<input type="submit" formaction="/NCHP/resetVerify.htm" value="Verify" class="btn btn-primary btn-block">
</span>
</div>
</div>
</form:form>
3) form to enter new password:
<form:form class="form-horizontal" name="resetPass" method="POST" id='resetPassForm' >
<div class="form-group has-feedback">
<i class="glyphicon glyphicon-lock form-control-feedback"></i>
<input type="password" id="newpass" name="newpass" placeholder="new Password" class="form-control" autofocus="autofocus">
</div>
<div class="form-group has-feedback">
<i class="glyphicon glyphicon-lock form-control-feedback"></i>
<input type="password" name="newpass2" id="newpass2" placeholder="re enter Password" class="form-control" autofocus="autofocus">
</div>
<div class="form-group" id="new-login-btn">
<div class="col-sm-12 ">
<span class="pull-right">
<input type="submit" formaction="/NCHP/changePass.htm" value="Save Password" onsubmit="modaljay();" class="btn btn-info btn-block">
<div class="modaljay"><!-- Place at bottom of page --></div>
</span>
</div>
</div>
</form:form>
The first two forms i do an ajax submit and get back just the data without a view like below with jquery $.ajax()
$('#resetForm').submit(function(event) {
$("#verifyModal").hide();
$("passModal").hide();
var resetmail = $('#resetEmail').val();
console.log(resetmail);
var json = {
"email" : resetmail
};
$.ajax({
url : "http://localhost:8080/NCHP/reset.htm",
data : json,
dataType : 'text json',
type : "POST",
success : function(e) {
$('#resetModal').modal('hide');
$("#verifyModal").modal('show');
console.log(e);
},
error : function(e) {
console.log(e);
if (e.responseText == "email sent") {
$('#resetModal').modal('hide');
$("#verifyModal").modal('show');
} else if (e.responseText == "email not sent. UNAUTHORIZED") {
$("#emailResponce").html("there was an error. We could not process your request at this time. Please contact support#nexiscard.com");
}
}
});
event.preventDefault();
});
The third form is a regular form submission and no ajax submission. because i want the user to be forwarded to their home page after they login with temp and set new password.
Below are the controller mappings for first two forms.
#Controller
public class UserLoginreset
{
#Autowired
public UserDao userDao;
#Autowired
public BCryptPasswordEncoder encoder;
#Autowired
public SecureServiceClient serviceClient;
#RequestMapping(value = "/reset", method = RequestMethod.POST)
public #ResponseBody String reset( #RequestBody(required=true) String email,
HttpServletRequest request)
{
String mail="";
try{
mail = java.net.URLDecoder.decode(email, "UTF-8").replace("email=", "");
}
catch (UnsupportedEncodingException e){
e.printStackTrace();
}
User user =userDao.findUserByemail(mail);
request.getSession().setAttribute("user",user);
String resetPwd= encoder.encode("xxxx");
if(user!=null && email!=null){
userDao.resetPass(user.getUser_name(), resetPwd);
return (String) serviceClient.returnRestTemplate("email", mail);//"home";
} else {
return "login";//"index";
}
}
#RequestMapping(value = "/resetVerify", method = RequestMethod.POST)
public #ResponseBody String resetVerify( #RequestParam(value="user",required=true) String user,#RequestParam(value="pass",required=true) String pass,
HttpServletRequest request)
{
User user1 =userDao.findUserByName(user);
if(user1!=null && pass.matches("xxxx")){
return "success";//"home";
} else {
return "unauthorised";//"index";
}
}
}
and third form.
#RequestMapping(value = "/changePass", method = RequestMethod.POST)
public #ResponseBody String resetPass( #RequestParam(value="newpass", required=true) String newpass, #RequestParam(value="newpass2", required=true) String newpass2,
HttpServletRequest request, Model model, HttpServletResponse httpServletResponse)
{
User user = (User)request.getSession(false).getAttribute("user");
if(user.getUser_name()!=null && newpass.matches(newpass2)){
userDao.resetPass(user.getUser_name(), encoder.encode(newpass));
String news = userDao.getDynamicNewsByUser(user.getUser_name());
model.addAttribute("user",user);
model.addAttribute("news", news);
return "MainLayout_Jay";//"home";
} else {
return "login";//"index";
}
}
And below is my spring config
<bean id="annotationResolver" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.nexis.cardholder" />
<mvc:annotation-driven >
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.nexis.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/Pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
<property name="order" value="1" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" >
<property name="order" value="2" />
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
<property name="order" value="0" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/views.xml</value>
</list>
</property>
</bean>
I have two issues.
1) The last form submission dosent return a view with the data in it. It just returns an empty page with controller method's return string in it.
2) I configured my home page in both tiles.xml and put it in /webcontent/pages folder. so if tiles view resolver could not find it, regular resolver should have. i doubt if its treating this request as a ajax request and skipping the model-view mapping part totally. how do i figure out the root cause.
2.5)if i want to parse ajax requests as Json, should i use #restcontroller and will it automatically send the responce as json? i tried using MappingJackson2HttpMessageConverter but didnt see any difference in debug mode?? did it even get used?
Got it. It didnt take as much time as typing this question.
i needed to remove the #ResponseBody annotation at
public #ResponseBody String resetPass(

How to navigate between html & jsp pages in spring

I have a Html page called kind.html inside the WEB-INF directory and an other jsp page called registration.jsp inside the WEB-INF folder. I need to put this registration.jsp page inside the WEB-INF directory so it cannot be accessible if a user attempts to get access to it by typing its URL. So my problem is how can i navigate from kind.html to registration.jsp with link called home I am newbie in this Thank you.
below is my code snippet and png file
kind.html..............................................
<li class='active'><a href='kind.html'><span>Home</span></a></li>
<li class='has-sub'><span>Register</span>
.............................registrationcontroller........................................
#RequestMapping(value="/registration",method = RequestMethod.POST)
public #ResponseBody
String firstRegistration(HttpServletRequest req,
HttpServletResponse response) {
response.setContentType("text/html");
RegistrationModel registrationModel = new RegistrationModel();
registrationModel.setFirstName(req.getParameter("first_name"));
System.out.println("controller " + req.getParameter("first_name") );
registrationModel.setLastName(req.getParameter("last_name"));
registrationModel.setPassword(req.getParameter("password"));
registrationModel.setEmailID(req.getParameter("email"));
System.out.println("controller email " + req.getParameter("email"));
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date = format.parse(req.getParameter("BirthDate"));
registrationModel.setDOB(date);
} catch (Exception e) {
e.printStackTrace();
}
String phoneno=req.getParameter("phoneNo");
Integer phoneNo = Integer.parseInt(phoneno);
System.out.println("phone no ...."+phoneNo);
registrationModel.setPhoneNo(phoneNo);
registrationModel.setGender(req.getParameter("gender"));
String age=req.getParameter("Age");
Long AGE = Long.parseLong(age);
registrationModel.setAge(AGE);
registrationModel.setAvtar(req.getParameter("Avtar"));
System.out.println("avtar"+ req.getParameter("Avtar"));
Address address = new Address();
address.setAddressline(req.getParameter("Full-Address"));
address.setCity(req.getParameter("city"));
address.setLandmark(req.getParameter("landmark"));
address.setState(req.getParameter("state"));
String zipCode =req.getParameter("Zipcode");
Long zipcode = Long.parseLong(zipCode);
address.setZipcode(zipcode);
registrationModel.setAddress(address);
registrationService.resgistration(registrationModel);
return "registration.jsp";
}
..........................registration.jsp.........................................................
<form action="registration" method="post">
<fieldset>
<legend>Register Form</legend>
<div>
<input type="text" name="first_name" placeholder="First Name" />
</div>
<div>
<input type="text" name="last_name" placeholder="Last Name" />
</div>
<div>
<input type="password" name="password" placeholder="Password" />
</div>
<div>
<input type="text" name="email" placeholder="Email" />
</div>
<div>
<input type="text" name="BirthDate" placeholder="BirthDate" />
</div>
<div>
<input type="number" name="Age" placeholder="Age" />
</div>
<div>
<select name="gender">
<option value="select">i am..</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select><br> <br>
</div>
<div>
<input type="number" name="phoneNo" placeholder="PhoneNo" />
</div>
<div>
<input type="text" name="Full-Address"
placeholder="Full-Address" />
</div>
<div>
<input type="text" name="landmark" placeholder="landmark" />
</div>
<div>
<input type="text" name="city" placeholder="city" />
</div>
<div>
<input type="text" name="state" placeholder="state" />
</div>
<div>
<input type="number" name="Zipcode" placeholder="Zipcode" />
</div>
<div>
<input type="file" name="Avtar" placeholder="Avtar" />
</div>
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>![folder structure of project][2]
1st to call your pages html is static so you can use mvc resources "" for it, for jsp you have to use ViewResolver for jstl use InternalResourceViewResolver in its configuration as :
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
then in your controller use
return "registration";
also you will need method to handle GET request and change below line
<li class='has-sub'><span>Register</span>
if you are using Spring boot you will find these configuration automated.

java vs. php in html form using post

I need send a form from php to java using the method post and curl.
I'm having problems to fetch a list of objects in php when I submit the form. I would like to know if is possible to do it like in Spring MVC (specifying attribute name in the form)
<form method="post" action="group_create.php">
<div>
Name: <input type="text" name="name" />
<br />
<input type="text" name="users[0].name" value="753" />
<br />
<input type="text" name="users[1].name" value="752" />
<br />
<input type="submit" value="Save" />
</div>
</form>
Encoding method:
<?php
http_build_query($_POST);
?>
Current curl url:
javaserver/app/groups/create?name=Administrator&users[0]=Tom&users[1]=Myke
Necessary curl url:
javaserver/app/groups/create?name=Administrator&users[0].name=Tom&users[1].name=Myke
My DTO's:
public class GroupDTO {
private String name;
private List<UserDTO> users;
public GroupDTO()
{
this.users = new ArrayList<UserDTO>();
}
}
public class UserDTO {
private String name;
}
Spring MVC Controller:
#Controller
#RequestMapping("secure/groups")
public class GroupsController {
#RequestMapping(value = "create", method = RequestMethod.POST)
public #ResponseBody ModelMap create(GroupDTO dto)
{
ModelMap map = new ModelMap();
//CODE TO DO ANYTHING
return map;
}
}
Change this:
<form method="post" action="group_create.php">
<div>
Name: <input type="text" name="name" />
<br />
<input type="text" name="users[0].name" value="753" />
<br />
<input type="text" name="users[1].name" value="752" />
<br />
<input type="submit" value="Save" />
</div>
</form>
To this:
<form method="post" action="group_create.php">
<div>
Name: <input type="text" name="name" />
<br />
<input type="text" name="users[0]" value="753" />
<br />
<input type="text" name="users[1]" value="752" />
<br />
<input type="submit" value="Save" />
</div>
</form>
The ".name" part is not needed for the form to operate properly.

Data not get bind with the Binding result in Spring mvc

I have been facing this problem for the past 2 days. Although I have gone through so many post I did not find a solution for my question.
Actually I was trying to validate my login form using Spring validations but even if I had given some wrong inputs it is not showing me any error , it accepts my every input.
For example, I have used #NotEmpty and #Email annotations for email it even accepts my plain inputs like "user". It has to throw the error as "Invalid email format" but this errors are not get bind into my Bindingresult.
My Controller : ContactController.java
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.loginform;
import javax.validation.Valid;
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
import net.viralpatel.spring3.form.loginform;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;#Controller{
#RequestMapping(value = "/get", method = RequestMethod.GET)
public String get(ModelMap model) {
loginform ud = new loginform();
ud.setUser("");
ud.setEmail("");
model.addAttribute("lform",ud);
return "login";
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public String loginCheck(#ModelAttribute("lform") #Valid loginform lform, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "login";
} else {
model.addAttribute("lfobj", lform);
return "success";
}
}
My login.jsp file :
<form:form action="login.html" commandName="lform">
<table>
<tr>
<td><font face="verdana" size="2px">User</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="user" /> <form:errors path="user"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Email</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="email" /> <form:errors path="email"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Phone</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="phone" /> <form:errors path="phone"></form:errors>
</font>
</td>
</tr>
<tr>
<td><font face="verdana" size="2px">Blog</font></td>
<td>:</td>
<td>
<font face="verdana" size="2">
<form:input path="blog" /> <form:errors path="blog"></form:errors>
</font>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
My loginform.java :
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.URL;
import org.springframework.validation.BindingResult;
public class loginform{
#NotEmpty
private String user;
#NotEmpty
#Email
private String email;
#NotEmpty(message = "Phone should not be blank.")
#Size(min = 10,max = 10)
private String phone;
#NotEmpty(message = "Enter your blog URL")
#URL
private String blog;
//get & set methods
}
My spring-servlet.xml :
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.spring3.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="props" />
</bean>
This is my first program in Spring validation so may be I hit low but kindly give any solutions for my issue.
Add this to your spring config:
<mvc:annotation-driven/>
This will enable Bean Validation.
Document: Reference
Your jsp form tag is missing the http method attribute method="POST (without this attribute for form data are submit an http GET, and this is bound to the request handler method):
<form:form method="POST" action="login.html" commandName="lform">...

Using #Valid is throwing exceptions & not working in basic Spring 3.0 MVC program

I am learning Spring MVC using Spring In Action 3rd Action, I have implemented the basic program which shows the user registration form and once we submit the form, it will be validated using #Valid.
Here is my Spring Controller:
#Controller
#RequestMapping("/spitter")
public class SpitterController {
private final SpitterService spitterService;
#Inject
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
Spittle spittle = new Spittle();
model.addAttribute(spittle);
model.addAttribute(new Spitter());
return "spittles/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "spittles/edit";
}
spitterService.saveSpitter(spitter);
return "redirect:/spitter/" + spitter.getUsername();
}
}
Here is my Spitter class file:
package com.habuma.spitter.domain;
import java.util.List;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class Spitter {
private Long id;
#Size(min = 3, max = 20, message = "User name must be between 3 and 20 characters long.")
#Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Username must be alphanumeric with no spaces")
private String username;
#Size(min = 6, max = 20, message = "The password must be atleast 6 characters long.")
private String password;
#Size(min = 3, max = 50, message = "Your full name must be between 3 and 50 characters long.")
private String fullName;
#Pattern(regexp = "[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", message = "Invalid email address.")
private String email;
private List<Spittle> spittles;
private boolean updateByEmail;
......Setters & Getters.....
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName)
&& other.username.equals(username)
&& other.password.equals(password);
}
#Override
public int hashCode() {
return super.hashCode();
}
}
This is my edit.jsp file which is shown to the user for registration:
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<div>
<h2>Create a free Spitter account</h2>
<sf:form method="POST" modelAttribute="spitter" enctype="multipart/form-data">
<fieldset>
<table cellspacing="0">
<tr>
<th><label for="user_full_name">Fullname:</label></th>
<td><sf:input path="fullName" size="15" id="user_full_name" />
<sf:errors path="fullName" cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_screen_name">Username:</label></th>
<td><sf:input path="username" size="15" maxlength="15"
id="user_screen_name" /> <small id="username_msg">No spaces,please.</small>
<sf:errors path="username" cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_password">Password:</label></th>
<td><sf:password path="password" size="30" showPassword="true"
id="user_password" /> <small>6
characters or more (betricky!)</small> <sf:errors path="password"
cssClass="error" /></td>
</tr>
<tr>
<th><label for="user_email">EmailAddress:</label></th>
<td><sf:input path="email" size="30" id="user_email" /> <small>In
case you forget something</small> <sf:errors path="email"
cssClass="error" /></td>
</tr>
<tr>
<th></th>
<td><sf:checkbox path="updateByEmail"
id="user_send_email_newsletter" /> <label
for="user_send_email_newsletter">Send me email updates!</label></td>
</tr>
<tr>
<th><label for="image">Profile image:</label></th>
<td><input name="image" type="file" />
</tr>
<tr>
<th></th>
<td><input name="commit" type="submit"
value="I accept.Createmyaccount." /></td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
To load the form I am accessing the URL as : http://localhost:8081/SpringInAction3/spitter?new, once the form is loaded I am just submitting the form without entering any details so that I can check if my form is getting validated or not. But I am getting below exception:
java.lang.NullPointerException
com.habuma.spitter.domain.Spitter.equals(Spitter.java:87)
org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver$TraversableHolder.equals(SingleThreadCachedTraversableResolver.java:138)
java.util.HashMap.get(HashMap.java:305)
org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:45)
org.hibernate.validator.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:757)
org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:324)
org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForRedefinedDefaultGroup(ValidatorImpl.java:273)
org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:256)
org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:210)
org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:119)
org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:106)
org.springframework.validation.DataBinder.validate(DataBinder.java:760)
I am getting NullPointerException in my equals method of Splitter class. Please let me know where I am doing mistake?
Edit:
When I tried to print the values of the fields in my Spitter object I am getting null for all the fields so that is causing the NullPointerException.
This time I removed the equals and hashCode methods from my Spitter class, now when I am submitting the form, the validation is not happening and the page is going to http://localhost:8081/SpringInAction3/spitter/null without showing any errors.
Why the validation is not happening in this case? Also if I just follow the steps in that book, I am getting NullPointerException which is not expected. Please let me know where I am doing mistake?
As per this SO post : #Valid (jsr 303) not working in Spring mvc 3.0, I also have the tag <mvc:annotation-driven/> in my configuration file.
I see one mistake so far. The sf:form attribute enctype is set as multipart/form-data but that is only used on file uploads, so i guess spring mvc is using the MultipartResolver instead of Data binding mechanism that binds form data to form backing objects , try changing it to application/x-www-form-urlencoded, which is the default and correct type for your case.

Categories

Resources