Spring MVC Textbox Example

In this example we learn how to create a Spring MVC form with a Textbox. Spring provides the “form” tag library which as simple as HTML form tags. Here we will create a simple Spring mvc form with two textbox and we will add validation support to check if it is not empty and size is between 1 and 5.

In Spring MVC we will use <form:input/> tag to render a textbox

<form:input path="firstName"/>

Which produces the below HTML code.

<input id="firstName" name="firstName" type="text" value=""/>

Folder Structure :

  1. Create a Dynamic Web Project SpringMVCFormHandling and create a package for our src files “com.javainterviewpoint
  2. Place the Spring 3 jar files under WEB-INF/Lib 

    commons-logging-1.1.1.jar
    log4j-1.2.16.jar
    slf4j-api-1.7.5.jar
    slf4j-log4j12-1.7.5.jar
    hibernate-validator-4.2.0.Final.jar
    spring-aspects-3.2.4.RELEASE.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar
    validation-api-1.1.0.Final.jar
    jstl-1.1.2.jar

  3. Create the Java classes MVC_Controller.java and RegistrationBean.java under  com.javainterviewpoint folder.
  4. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  5. View files SpringMVC_TextBoxExample.jsp and Success.jsp are put under the sub directory under WEB-INF/Jsp

MVC_Controller.java

  • The DispatcherServlet mapping which we make in the web.xml will delegate the all the request to our MVC_Controller as we have annotated it with @Controller annotation.
  • We use the @RequestMapping annotation to map each of the request which we get to individual methods. Our controller has two methods initializeForm() and  processForm(). 
  • The firstMethod (initializeForm) will take the user to the “SpringMVC_TextBoxExample” which is our view component with form backing object RegistrationBean.
  •  The Second method (processForm) will get called when the user submits the form. There the RegistrationBean object “rb”  will be validated as we have annotated with @Valid annotation and the validation results will be added to the BindingResult. Based on the result we will re-direct the user back to the “SpringMVC_TextBoxExample” or “Success” page.
package com.javainterviewpoint;

import javax.validation.Valid;

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;

@Controller
public class MVC_Controller 
{
	@RequestMapping("/TextBoxExample")
	public ModelAndView initializeForm()
	{
		return new ModelAndView("SpringMVC_TextBoxExample","rb",new RegistrationBean());
	}
	@RequestMapping(value="/check",method=RequestMethod.POST)
	public String processForm(@Valid @ModelAttribute("rb")RegistrationBean rb,BindingResult result)
	{
		if(result.hasErrors())
		{
			return "SpringMVC_TextBoxExample";
		}
		else
		{
			return "Success";
		}
		
	}
}

Model (RegistrationBean.java)

Our RegistrationBean act as a Model here, which has two String properties firstName and lastName, which has it own getters and setters so that it can be accessed from the view.

We have added the annotation @NotEmpty and @Size to check if the fields are not empty and size is between 1 and 5. We have added the respective custom error messages in the props.property file.

package com.javainterviewpoint;

import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;

public class RegistrationBean 
{
	@NotEmpty
	@Size(min=1,max=5)
	String firstName;
	
	@NotEmpty
	@Size(min=1,max=5)
	String lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

View

Our view component has two text fields firstName and lastName generated by using the Spring form tag library. The <form:form> has a noticeable property called as the “commandName” which has the name of the backing bean that is binded in the model(RegistrtationBean rb) .

<form:errors> tag displays the error message which occurs during the validation

SpringMVC_TextBoxExample.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
 <%@ 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>Insert title here</title>
<style>
.error {
 color: #ff0000;
}
 
.commonerrorblock {
 color: #000;
 background-color: #ffEEEE;
 border: 3px solid #ff0000;
 
}
</style>
</head>
<body>
 <form:form action="check" method="post" commandName="rb">
 <form:errors path="*" element="div" cssClass="commonerrorblock"/>
 <table>
 <tr>
 <td>FirstName</td>
 <td><form:input path="firstName"/></td>
 <td><form:errors path="firstName" cssClass="error"/></td>
 </tr>
 <tr>
 <td>LastName</td>
 <td><form:input path="lastName"/></td>
 <td><form:errors path="lastName" cssClass="error"/></td>
 </tr>
 <tr>
 <td></td><td><input type="submit"></td><td></td>
 </tr>
 </table>
 </form:form>
</body>
</html>

props.properties

NotEmpty.rb.firstName=Please enter a valid FirstName
Size.rb.firstName    = FirstName size should be between 1 and 5
NotEmpty.rb.lastName=Please enter a valid LastName
Size.rb.lastName    = LastName size should be between 1 and 5

Success.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h2>Welcome ${{rb.firstName}</h2>
</body>
</html>

Configurations

web.xml

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory. <servlet-name> contains the name of the SpringConfiguration , when the DispatcherServlet is initialized the framework will try to load a configuration file “[servlet-name]-servlet.xml” under the WEB-INF directory.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee%20http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <display-name>SpringMVCFormHandling</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
 <servlet-name>SpringConfig</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>SpringConfig</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

SpringConfig-servlet.xml

  • The SpringConfig-servlet.xml is also placed under the WEB-INF directory.
  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”. 
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Valid etc annotations.
  • The view is resolved through “org.springframework.web.servlet.view.InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.
  • Resource Bundle is accessed through the “org.springframework.context.support.ResourceBundleMessageSource”  through its property “basename” which has the value “props”, and hence our property file should “props.properties”
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation=" http://www.springframework.org/schema/beans%20
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd%20
 http://www.springframework.org/schema/context%20
 http://www.springframework.org/schema/context/spring-context-3.0.xsd%20
 http://www.springframework.org/schema/mvc%20
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
 
 <context:component-scan base-package="com.javainterviewpoint"/>
 <mvc:annotation-driven/>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <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"></property>
 </bean>
</beans>

Lets run our application

Now lets run our application, do a clean build and deploy the application in the Server

Hit on the url “http://localhost:8080/SpringMVCFormHandling/TextBoxExample”

SpringMVC_TextBoxExample

 

Click on Submit without entering any data, you will be thrown up the validation errors as below.

SpringMVC_TextBoxExample_Validation

 

Once you enter the correct values and submit, the user will be redirected the Success page.

SpringMVC_TextBoxExample_Success

Comments

  1. Tanaya Karmakar says

    Hi , I have followed the exact steps mentioned over here , I am using jdk 1.8 and Tomcat 8 , while I am trying to run the example I am getting the below mentioned error

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘messageSource’ defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.MessageSourceResourceBundle]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceResourceBundle.()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.context.support.AbstractApplicationContext.initMessageSource(AbstractApplicationContext.java:786)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:467)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:817)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.context.support.MessageSourceResourceBundle]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceResourceBundle.()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
    … 36 more
    Caused by: java.lang.NoSuchMethodException: org.springframework.context.support.MessageSourceResourceBundle.()
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getDeclaredConstructor(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
    … 37 more

    • javainterviewpoint says

      Karmakar
      It seems there is some jar missing or the version conflict of jar. Check if you have spring-context.3.2.4.jar or check the xsd used in xml.

Leave a Reply

Your email address will not be published. Required fields are marked *