Data not get bind with the Binding result in Spring mvc - java

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">...

Related

I can't access jsp page using Spring MVC 3

I created simple add entity form called addContact.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h2>Contact information</h2>
<form:form method="POST" action="contacts/add" modelAttribute="contact">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="surname">Surname</form:label></td>
<td><form:input path="surname" /></td>
</tr>
<tr>
<td><form:label path="phonenumber">Phonenumber</form:label></td>
<td><form:input path="phonenumber" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Here is rest-handler-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="facade.rest" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Here is servlet-mapping from web.xml
<servlet-mapping>
<servlet-name>rest-handler</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And, finally a controller:
package facade.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
import domain.ContactDO;
import service.IContactService;
#Controller
public class ContactController {
private IContactService contactService;
#Required
public void setContactService(IContactService contactService) {
this.contactService = contactService;
}
#RequestMapping(value = "/contacts", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<List<ContactDO>> getContacts() {
List<ContactDO> contacts = contactService.load();
if(contacts != null) {
return new ResponseEntity<>(contacts, HttpStatus.OK);
}
else
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#RequestMapping(value = "/contacts/{id:.*}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<ContactDO> getContact(#PathVariable Integer id) {
ContactDO contact = contactService.loadContact(id);
if(contact != null) {
return new ResponseEntity<>(contact, HttpStatus.OK);
}
else
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
#RequestMapping(value = "/contacts/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") ContactDO contact, ModelMap model) {
model.addAttribute("name", contact.getName());
model.addAttribute("surname", contact.getSurname());
model.addAttribute("phonenumber", contact.getPhonenumber());
//contact.setId(2);
contactService.store(contact);
return "contacts";
}
}
When I am trying to access from at http://localhost:8080/pb/contacts/add (pb is a name of war) I get HTTP 400. Logs tell that I'm trying to do a get request.
When I am trying to access from at
http://localhost:8080/pb/contacts/add (pb is a name of war) I get HTTP
400. Logs tell that I'm trying to do a get request.
That is right !! you are trying /contacts/add using a GET request and the Request Handler can not map your request because /contacts/add is only accessible through a POST request. Look at your method definition:
#RequestMapping(value = "/contacts/add", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact") ContactDO contact, ModelMap model) {
}
you need a POST request to reach your method.
EDIT: I suppose you want to edit a contact with your /contacts/add method. If this is the case, then please first call /contacts/{id:.*} with id being the id of you contact. and then there you can make your edit and send your post by submitting your edit. That is how you reach you /contacts/add page.
If you don't know any id, then call first http://localhost:8080/pb/contacts
for your contacts. there your will (hopefully) find your contact to edit.
EDIT**: On your rest client, have you tried changing the type of request the to POST?

spring:bind and JSR-303 validation. Unable to show error messages on page when validation fails

I need some help. I have a trouble working on my pet project. It's simple crud app based on spring mvc. The trouble is that I can't get error messages when input validation fails in my profile.jsp. I have mostly the same code in my signup.jsp but there all works fine.
There is my controller methods:
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public String getUserProfile(Model model) {
model.addAttribute("userDetailsForm", new UserDetailsFormDTO());
model.addAttribute("passwordForm" ,new PasswordFormDTO());
model.addAttribute("profile", getCurrentUser());
return "profile";
}
#RequestMapping(value = "/profile/details/change", method = RequestMethod.POST)
public String changeUserDetails(#ModelAttribute("userDetailsForm") #Valid UserDetailsFormDTO form,
BindingResult result) {
if(result.hasErrors()){
result.getAllErrors().forEach(log::debug);
return "redirect:/profile";
}
userService.changeUserDetails(getCurrentUser(), form);
return "redirect:/profile?success=details";
}
I'm using JSR 303 Validation:
package org.crud.dto;
import java.io.Serializable;
import javax.validation.constraints.Pattern;
import org.crud.validation.InputValidator;
import org.hibernate.validator.constraints.NotEmpty;
public class UserDetailsFormDTO implements Serializable{
private static final long serialVersionUID = -7603395840362468805L;
#NotEmpty(message="{error.null_form_value}")
#Pattern(regexp=InputValidator.FIRSTNAME_PATTERN, message="{error.name_invalid}")
private String firstName;
#NotEmpty(message="{error.null_form_value}")
#Pattern(regexp=InputValidator.LASTNAME_PATTERN, message="{error.name_invalid}")
private String lastName;
public UserDetailsFormDTO() {}
public UserDetailsFormDTO(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
In configuration files I have next beans declared:
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"
p:validationMessageSource-ref="messageSource" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
Also have two .properties files with my labels and error codes on my classpath: messages_ru and messages_en.
My profile.jsp code fragment:
<div id="user-details-upd" class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Update user details</h3>
</div>
<div class="panel-body">
<div class="container-fluid">
<form name="userDetailsForm" class="form-horizontal" role="form" method="POST" action="profile/details/change">
<spring:bind path="userDetailsForm"></spring:bind>
<div class="form-group">
<div class="row">
<label for="fname-input" class="col-md-offset-2 col-md-2 control-label">First name:</label>
<div class="col-md-5">
<spring:message code="label.fname_placeholder" var="fNameHolder" />
<spring:bind path="userDetailsForm.firstName">
<input type="text" value="${profile.getFirstName()}" name="<c:out value="${status.expression}"/>" class="form-control" placeholder="${fNameHolder}" required>
<c:if test="${status.error}">
<c:forEach items="${status.errorMessages}" var="error">
<small class="text-danger"> <c:out value="${error}" />
</small>
</c:forEach>
</c:if>
</spring:bind>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label for="lname-input" class="col-md-offset-2 col-md-2 control-label">Last name:</label>
<div class="col-md-5">
<spring:message code="label.lname_placeholder" var="lNameHolder" />
<spring:bind path="userDetailsForm.lastName">
<input type="text" value="${profile.getLastName()}" name="<c:out value="${status.expression}"/>" class="form-control" placeholder="${lNameHolder}" required>
<c:if test="${status.error}">
<c:forEach items="${status.errorMessages}" var="error">
<small class="text-danger"> <c:out value="${error}" />
</small>
</c:forEach>
</c:if>
</spring:bind>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-offset-4 col-md-5">
<button type="submit" value="Submit" class="btn btn-success">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Update
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
And message from debug when I submit incorrect data in lastName input:
2015-08-07 18:52:29 DEBUG UserController:? - Field error in object 'userDetailsForm' on field 'lastName': rejected value [jh]; codes [Pattern.userDetailsForm.lastName,Pattern.lastName,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userDetailsForm.lastName,lastName]; arguments []; default message [lastName],[Ljavax.validation.constraints.Pattern$Flag;#657f42ee,([A-Z�-�][a-zA-Z�-�]*)([\s\'-][A-Z�-�][a-z�-�]*)*]; default message [Name must contain only characters and first letter must be in uppercase]
I can't understand, why status.errorMessages is empty when BindingResult has got errors?
Any help or suggestions are appreciated.
Thanks in advance
You are using redirects within the request mapping block of your controller. The redirect is a header sent to the browser. The browser initiates the redirect, consequently you get a totally new request from the browser and because http is stateless, you lose anything stored in that previous request/response, such as the BindingResult.
remove the redirects and use a string to forward to the jsp page. You can use the internalviewresolver for this

Spring MVC validations Not working

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

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.

Post function not binding in Spring 3.0

This may have been asked many times but I have not been able to find a concrete answer over last two days. Using Spring 3.2.
I have two methods. One is for form creation and the other is for the form to post. Form creation works fine. But when I try to post/submit the form, I don't see the log statement getting executed in the login() method and I get a 404 error HTTP Status 404 - /sample/login.
I think the problem is the form cannot submit to URL but I don`t know how to fix the mapping to make it work.
If there are any other files that are needed please let me know. BTW following example from sprin/mvc-basic and spring/petclinic
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 example.domain.User;
import example.service.UserValidator;
#Controller
#RequestMapping(value="/login")
public class LoginFormController {
protected final Log logger = LogFactory.getLog(getClass());
#RequestMapping(method=RequestMethod.GET)
public String loadForm(Model model) {
logger.info("LoginFormController login");
model.addAttribute("user", User.getUserInstance());
return "login";
}
#RequestMapping(method=RequestMethod.POST)
public String login(#ModelAttribute User user, BindingResult result) {
logger.info("post");
new UserValidator().validate(user, result);
if (result.hasErrors()) {
return "login";
} else {
logger.info("Email Id: " + user.getEmailId());
//this.clinic.storeOwner(owner);
//status.setComplete();
return "redirect:/landing/" + user.getEmailId();
}
}
}
login.jsp
<%# include file="/WEB-INF/jsp/include.jsp"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title><fmt:message key="title" /></title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1>
<fmt:message key="login.heading" />
</h1>
<form:form method="post" modelAttribute="user" action="login">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td align="right" width="20%"><form:label for="emailId" path="emailId" cssErrorClass="error">Email ID:</form:label></td>
<td width="20%"><form:input path="emailId" /></td>
<td width="60%"><form:errors path="emailId" cssClass="error" /></td>
</tr>
<tr>
<td align="right" width="20%"><form:label for="password" path="password" cssErrorClass="error">Password:</form:label></td>
<td width="20%"><form:input path="password" /></td>
<td width="60%"><form:errors path="password" cssClass="error" /></td>
</tr>
</table>
<br>
<input type="submit" align="center" value="Login">
</form:form>
Signup
</body>
</html>
name-servlet.xml
<bean....>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</bean>
Your help appreciated.
Seems you have mapped *.htm URL to DispatcherServlet (Guessing from /signup.htm). Change the action in your form tag to login.htm instead of login:
<form:form method="post" modelAttribute="user" action="login.htm">

Categories

Resources