0% found this document useful (0 votes)
73 views65 pages

Spring MVC

Spring MVC is a Java framework that follows the MVC design pattern for building web applications. It uses the DispatcherServlet as a front controller to receive incoming requests and map them to controllers. The controller returns a model and view, which are then used by the view resolver to render the view page. Spring MVC separates roles like controllers, models, and views and provides features like inversion of control, dependency injection, and flexible mapping between URLs and controllers.

Uploaded by

Dulam Tataji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
73 views65 pages

Spring MVC

Spring MVC is a Java framework that follows the MVC design pattern for building web applications. It uses the DispatcherServlet as a front controller to receive incoming requests and map them to controllers. The controller returns a model and view, which are then used by the view resolver to render the view page. Spring MVC separates roles like controllers, models, and views and provides features like inversion of control, dependency injection, and flexible mapping between URLs and controllers.

Uploaded by

Dulam Tataji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 65

Spring MVC

A Spring MVC is a Java framework which is used to build web applications. It follows the
Model-View-Controller design pattern. It implements all the basic features of a core spring
framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views.

Spring Web Model-View-Controller

o Model - A model contains the data of the application. A data can be a single
object or a collection of objects.
o Controller - A controller contains the business logic of an application. Here, the
@Controller annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format.
Generally, JSP+JSTL is used to create a view page. Although spring also supports
other view technologies such as Apache Velocity, Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the
front controller. It is responsible to manage the flow of the Spring MVC
application.

Understanding the flow of Spring Web MVC


o As displayed in the figure, all the incoming request is intercepted by the
DispatcherServlet that works as the front controller.
o The DispatcherServlet gets an entry of handler mapping from the XML file and
forwards the request to the controller.
o The controller returns an object of ModelAndView.
o The DispatcherServlet checks the entry of view resolver in the XML file and
invokes the specified view component.

Advantages of Spring MVC Framework


o Separate roles - The Spring MVC separates each role, where the model object,
controller, command object, view resolver, DispatcherServlet, validator, etc. can
be fulfilled by a specialized object.
o Light-weight - It uses light-weight servlet container to develop and deploy your
application.
o Powerful Configuration - It provides a robust configuration for both framework
and application classes that includes easy referencing across contexts, such as
from web controllers to business objects and validators.
o Rapid development - The Spring MVC facilitates fast and parallel development.
o Reusable business code - Instead of creating new objects, it allows us to use the
existing business objects.
o Easy to test - In Spring, generally we create JavaBeans classes that enable you to
inject test data using the setter methods.
o Flexible Mapping - It provides the specific annotations that easily redirect the
page.

Spring Web MVC Framework Example


Steps:
o Load the spring jar files or add dependencies in the case of Maven
o Create the controller class
o Provide the entry of controller in the web.xml file
o Define the bean in the separate XML file
o Display the message in the JSP page
o Start the server and deploy the project

1. Provide project information and configuration in the pom.xml


file.

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  

. Create the controller class


To create the controller class, we are using two annotations @Controller and
@RequestMapping.

The @Controller annotation marks this class as Controller.

The @Requestmapping annotation is used to map the class with the specified URL
name.

HelloController.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
@Controller  
public class HelloController {  
@RequestMapping("/")  
    public String display()  
    {  
        return "index";  
    }     
}  

3. Provide the entry of controller in the web.xml file


In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front
controller in Spring Web MVC. All the incoming request for the html file will be
forwarded to the DispatcherServlet.
web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

4. Define the bean in the xml file


This is the important configuration file where we need to specify the View components.

The context:component-scan element defines the base-package where


DispatcherServlet will search the controller class.

This xml file should be located inside the WEB-INF directory.

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
  
</beans>  

5. Display the message in the JSP page


This is the simple JSP page, displaying the message returned by the Controller.

index.jsp

<html>  
<body>  
<p>Welcome to Spring MVC Tutorial</p>  
</body>  
</html>  

Spring MVC Multiple View page Example


. Add dependencies to pom.xml
 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  

2. Create the request page


Let's create a simple jsp page containing a link.

index.jsp

<html>  
<body>  
<a href="hello">Click here...</a>  
</body>  
</html> 

3. Create the controller class


Let's create a controller class that returns the JSP pages. Here, we pass the specific name
with a @Requestmapping annotation to map the class.

HelloController.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
@Controller  
public class HelloController {  
@RequestMapping("/hello")  
    public String redirect()  
    {  
        return "viewpage";  
    }     
@RequestMapping("/helloagain")  
public String display()  
{  
    return "final";  
}  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


Now, we also provide view resolver with view component.

Here, the InternalResourceViewResolver class is used for the ViewResolver.

The prefix+string returned by controller+suffix page will be invoked for the view
component.
This xml file should be located inside the WEB-INF directory.

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
<!-- Define Spring MVC view resolver -->  
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>          
     </bean>  
</beans>  

6. Create the other view components


viewpage.jsp

<html>  
<body>  
<a href="helloagain">SpringMVC</a>  
</body>  
</html>  

final.jsp

<html>  
<body>  
<p>Welcome to Spring MVC Tutorial</p>  
</body>  
</html>  

Spring MVC Multiple Controller Example


In Spring MVC, we can create multiple controllers at a time. It is required to map each
controller class with @Controller annotation. Here, we see a Spring MVC example of
multiple controllers.

1. Add dependencies to pom.xml


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
2. Create the request page
Let's create a simple JSP page containing two links.

index.jsp

<html>  
<body>  
<a href="hello1">Spring MVC</a> ||  
<a href="hello2">Spring Boot</a>  
</body>  
</html>  

3. Create the controller class


Let's create two controller classes, where each returns the particular view page.

HelloController1.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
@Controller  
public class HelloController1 {  
@RequestMapping("/hello1")  
    public String display()  
    {  
        return "viewpage1";  
    }     
}  

HelloController2.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
@Controller  
public class HelloController2 {  
@RequestMapping("/hello2")  
    public String display()  
    {  
        return "viewpage2";  
    }     
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>          
     </bean>  
</beans>  

6. Create the other view components


viewpage1.jsp

<html>  
<body>  
<p>Welcome to Spring MVC Tutorial</p>  
</body>  
</html>  

Viewpage2.jsp

<html>  
<body>  
<p>Welcome to Spring Boot Tutorial</p>  
</body>  
</html>  

Spring MVC Model Interface


In Spring MVC, the model works a container that contains the data of the application.
Here, a data can be in any form such as objects, strings, information from the database,
etc.

It is required to place the Model interface in the controller part of the application. The


object of HttpServletRequest reads the information provided by the user and pass it to
the Model interface. Now, a view page easily accesses the data from the model part.

1. Add dependencies to pom.xml


<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  

2. Create the request page


Here, we create the login page to receive name and password from the user.

index.jsp

<html>  
<body>  
<form action="hello">  
UserName : <input type="text" name="name"/> <br><br>  
Password : <input type="text" name="pass"/> <br><br>   
<input type="submit" name="submit">  
</form>  
</body>  
</html>  

3. Create the controller class


In controller class:

o The HttpServletRequest is used to read the HTML form data provided by the user.
o The Model contains the request data and provides it to view page.

HelloController.java

package com.java;  
import javax.servlet.http.HttpServletRequest;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@Controller  
public class HelloController {  
  
    @RequestMapping("/hello")  
    public String display(HttpServletRequest req,Model m)  
    {  
        //read the provided form data  
        String name=req.getParameter("name");  
        String pass=req.getParameter("pass");  
        if(pass.equals("admin"))  
        {  
            String msg="Hello "+ name;  
            //add a message to the model  
            m.addAttribute("message", msg);  
            return "viewpage";  
        }  
        else  
        {  
            String msg="Sorry "+ name+". You entered an incorrect password";  
            m.addAttribute("message", msg);  
            return "errorpage";  
        }     
    }  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>          
     </bean>  
</beans>  

6. Create the other view components


To run this example, the following view components must be located inside the WEB-
INF/jsp directory.

viewpage.jsp

<html>  
<body>  
${message}  
</body>  
</html>  
errorpage.jsp

<html>  
<body>  
${message}  
<br><br>  
<jsp:include page="/index.jsp"></jsp:include>  
</body>  
</html> 

Spring MVC RequestParam Annotation


In Spring MVC, the @RequestParam annotation is used to read the form data and bind
it automatically to the parameter present in the provided method. So, it ignores the
requirement of HttpServletRequest object to read the provided data.

Including form data, it also maps the request parameter to query parameter and parts in
multipart requests. If the method parameter type is Map and a request parameter name
is specified, then the request parameter value is converted to a Map else the map
parameter is populated with all request parameter names and values.

Spring MVC RequestParam Example


Let's create a login page that contains a username and password. Here, we validate the
password with a specific value.

1. Add dependencies to pom.xml


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  

2. Create the request page


It is the login page that receive name and password from the user.

Hello Java Program for Beginners

index.jsp

<html>  
<body>  
<form action="hello">  
UserName : <input type="text" name="name"/> <br><br>   
Password : <input type="text" name="pass"/> <br><br>   
<input type="submit" name="submit">  
</form>  
</body>  
</html>  

3. Create the Controller Class


In controller class:

o The @RequestParam is used to read the HTML form data provided by a user and bind it
to the request parameter.
o The Model contains the request data and provides it to view page.

HelloController.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
  
@Controller  
public class HelloController {  
  
    @RequestMapping("/hello")  
    //read the provided form data  
    public String display(@RequestParam("name") String name,@RequestParam("pass") String pa
ss,Model m)  
    {  
        if(pass.equals("admin"))  
        {  
            String msg="Hello "+ name;  
            //add a message to the model  
            m.addAttribute("message", msg);  
            return "viewpage";  
        }  
        else  
        {  
            String msg="Sorry "+ name+". You entered an incorrect password";  
            m.addAttribute("message", msg);  
            return "errorpage";  
        }     
    }  
}  

4. Create the other view components


To run this example, the following view components must be located inside the WEB-
INF/jsp directory.

viewpage.jsp

<html>  
<body>  
${message}  
</body>  
</html>  
errorpage.jsp
<html>  
<body>  
${message}  
<br><br>  
<jsp:include page="/index.jsp"></jsp:include>  
</body>  
</html>  

Spring MVC Form Tag Library


The Spring MVC form tags are the configurable and reusable building blocks for a web
page. These tags provide JSP, an easy way to develop, read and maintain.

The Spring MVC form tags can be seen as data binding-aware tags that can
automatically set data to Java object/bean and also retrieve from it. Here, each tag
provides support for the set of attributes of its corresponding HTML tag counterpart,
making the tags familiar and easy to use.

Configuration of Spring MVC Form Tag


The form tag library comes under the spring-webmvc.jar. To enable the support for form
tag library, it is required to reference some configuration. So, add the following directive
at the beginning of the JSP page:

1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  

List of Spring MVC Form Tags


Let's see some of the frequently used Spring MVC form tags.
Form Tag Description

form:form It is a container tag that contains all other form tags.

form:input This tag is used to generate the text field.

form:radiobutton This tag is used to generate the radio buttons.

form:checkbox This tag is used to generate the checkboxes.

form:password This tag is used to generate the password input field.

form:select This tag is used to generate the drop-down list.

form:textarea This tag is used to generate the multi-line text field.

form:hidden This tag is used to generate the hidden input field.

The form tag


The Spring MVC form tag is a container tag. It is a parent tag that contains all the other
tags of the tag library. This tag generates an HTML form tag and exposes a binding path
to the inner tags for binding.

Syntax
<form:form action="nextFormPath" modelAttribute=?abc?>  

Example of Spring MVC Form Text Field


1. Add dependencies to pom.xml file.
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  

2. Create the bean class


Here, the bean class contains the variables (along setter and getter methods)
corresponding to the input field exist in the form.

Reservation.java

package com.java.model;  
  
public class Reservation {  
  
    private String firstName;  
    private String lastName;  
          public Reservation()  
   {         
    }  
    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;  
    }     
}  

3. Create the controller class


ReservationController.java

package com.java.controller;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@RequestMapping("/reservation")  
@Controller  
public class ReservationController {  
    @RequestMapping("/bookingForm")  
public String bookingForm(Model model)  
{  
      //create a reservation object   
    Reservation res=new Reservation();  
      //provide reservation object to the model   
    model.addAttribute("reservation", res);  
    return "reservation-page";  
}  
@RequestMapping("/submitForm")  
// @ModelAttribute binds form data to the object  
public String submitForm(@ModelAttribute("reservation") Reservation res)  
{  
    return "confirmation-page";  
}  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
   <!--Provide support for conversion, formatting and validation -->  
  <mvc:annotation-driven/>  
    <!-- Define Spring MVC view resolver -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView
Resolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>       
     </bean>  
</beans>  

6. Create the requested page


index.jsp

<!DOCTYPE html>  
<html>  
<head>  
    <title>Railway Registration Form</title>  
</head>  
<body>  
<a href="reservation/bookingForm">Click here for reservation.</a>  
</body>  
</html>  

7. Create other view components


reservation-page.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>Reservation Form</title>  
</head>  
<h3>Railway Reservation Form</h3>  
<body>  
    <form:form action="submitForm" modelAttribute="reservation">  
        First name: <form:input path="firstName" />         
        <br><br>  
        Last name: <form:input path="lastName" />  
        <br><br>  
        <input type="submit" value="Submit" />      
    </form:form>  
</body>  
</html>  

Note - The value passed with the @ModelAttribute annotation should be the same to
the modelAttribute value present in the view page.

confirmation-page.jsp

<!DOCTYPE html>  
<html>  
<body>  
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>  
First Name : ${reservation.firstName} <br>  
Last Name : ${reservation.lastName}  
</body>  
</html>  

Spring MVC Form Radio Button


The Spring MVC form radio button allows us to choose only one option at a time. This tag
renders an HTML input tag of type radio.

Syntax
1. <form:radiobutton path="abc" value="xyz"/>  

Apart from radio button tag, Spring MVC form tag library also contains radiobuttons tag. This
tag renders multiple HTML input tags with type radio.

1. <form:radiobuttons path="abc" items="${xyz}"/>  

Example of Spring MVC Form Radio Button


1. Add dependencies to pom.xml
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  

2. Create the bean class


Reservation.java

package com.java;  
  
public class Reservation {  
  
    private String firstName;  
    private String lastName;  
    private String Gender;  
      
    public Reservation()  
    {         
    }  
    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;  
    }  
    public String getGender() {  
        return Gender;  
    }  
    public void setGender(String gender) {  
        Gender = gender;  
    }     
}  

3. Create the controller class


ReservationController.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@RequestMapping("/reservation")  
@Controller  
public class ReservationController {  
    @RequestMapping("/bookingForm")  
public String bookingForm(Model model)  
{  
      //create a reservation object   
    Reservation res=new Reservation();  
      //provide reservation object to the model   
    model.addAttribute("reservation", res);  
    return "reservation-page";  
}  
@RequestMapping("/submitForm")  
public String submitForm(@ModelAttribute("reservation") Reservation res)  
{  
    return "confirmation-form";  
}  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
   <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
    <!-- Define Spring MVC view resolver -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceView
Resolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>       
     </bean>  
</beans>  

6. Create the requested page


index.jsp

<!DOCTYPE html>  
<html>  
<head>  
    <title>Railway Registration Form</title>  
</head>  
<body>  
<a href="reservation/bookingForm">Click here for reservation.</a>  
</body>  
</html>  
7. Create the view components
reservation-page.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>Reservation Form</title>  
</head>  
<h3>Railway Reservation Form</h3>  
<body>  
    <form:form action="submitForm" modelAttribute="reservation">  
        First name: <form:input path="firstName" />         
        <br><br>  
        Last name: <form:input path="lastName" />  
        <br><br>  
        Gender:   
        Male <form:radiobutton path="Gender" value="Male"/>  
        Female <form:radiobutton path="Gender" value="Female"/>  
        <br><br>  
        <input type="submit" value="Submit" />  
    </form:form>  
</body>  
</html>  

confirmation-page.jsp

<!DOCTYPE html>  
<html>  
<body>  
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>  
First Name : ${reservation.firstName} <br>  
Last Name : ${reservation.lastName} <br>  
Gender: ${reservation.gender}  
</body>  
</html>

Example of Spring MVC Form Drop-Down List


1. Add dependencies to pom.xml file.

          <!-- https://mvnrepository.com/artifact/org.springframework/spring-
webmvc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  
2. Create the bean class
Reservation.java

package com.java;  
  
public class Reservation {  
  
    private String firstName;  
    private String lastName;  
    private String Gender;  
    private String[] Food;  
    private String cityFrom;  
    private String cityTo;  
    public Reservation()  
    {         
    }  
    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;  
    }  
    public String getGender() {  
        return Gender;  
    }  
    public void setGender(String gender) {  
        Gender = gender;  
    }  
    public String[] getFood() {  
        return Food;  
    }  
    public void setFood(String[] food) {  
        Food = food;  
    }     
    public String getCityFrom() {  
    return cityFrom;  
}  
public void setCityFrom(String cityFrom) {  
    this.cityFrom = cityFrom;  
}  
public String getCityTo() {  
    return cityTo;  
}  
public void setCityTo(String cityTo) {  
    this.cityTo = cityTo;  
}     
}  

3. Create the controller class


ReservationController.java

package com.java;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@RequestMapping("/reservation")  
@Controller  
public class ReservationController {  
    @RequestMapping("/bookingForm")  
public String bookingForm(Model model)  
{  
      //create a reservation object   
    Reservation res=new Reservation();  
      //provide reservation object to the model   
    model.addAttribute("reservation", res);  
    return "reservation-page";  
}  
@RequestMapping("/submitForm")  
public String submitForm(@ModelAttribute("reservation") Reservation res)  
{  
    return "confirmation-page";  
}  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  
5. Define the bean in the xml file
spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
    <!-- Define Spring MVC view resolver -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>       
     </bean>  
</beans>  

6. Create the requested page


index.jsp

<!DOCTYPE html>  
<html>  
<head>  
    <title>Railway Registration Form</title>  
</head>  
<body>  
<a href="reservation/bookingForm">Click here for reservation.</a>  
</body>  
</html>  

7. Create the view components


reservation-page.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>Reservation Form</title>  
</head>  
<h3>Railway Reservation Form</h3>  
<body>  
    <form:form action="submitForm" modelAttribute="reservation">  
        First name: <form:input path="firstName" />         
        <br><br>  
        Last name: <form:input path="lastName" />  
        <br><br>  
        Gender:   
        Male<form:radiobutton path="Gender" value="Male"/>  
        Female<form:radiobutton path="Gender" value="Female"/>  
        <br><br>  
        Meals:  
        BreakFast<form:checkbox path="Food" value="BreakFast"/>  
        Lunch<form:checkbox path="Food" value="Lunch"/>  
        Dinner<form:checkbox path="Food" value="Dinner"/>  
        <br><br>  
        Leaving from: <form:select path="cityFrom">  
        <form:option value="Ghaziabad" label="Ghaziabad"/>  
        <form:option value="Modinagar" label="Modinagar"/>  
        <form:option value="Meerut" label="Meerut"/>  
        <form:option value="Amristar" label="Amristar"/>  
        </form:select>  
        <br><br>  
        Going to: <form:select path="cityTo">  
        <form:option value="Ghaziabad" label="Ghaziabad"/>  
        <form:option value="Modinagar" label="Modinagar"/>  
        <form:option value="Meerut" label="Meerut"/>  
        <form:option value="Amristar" label="Amristar"/>  
        </form:select>  
        <br><br>  
        <input type="submit" value="Submit" />  
    </form:form>  
</body>  
</html>  

confirmation-page.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!DOCTYPE html>  
<html>  
<body>  
<p>Your reservation is confirmed successfully. Please, re-check the details.</p>  
First Name : ${reservation.firstName} <br>  
Last Name : ${reservation.lastName} <br>  
Gender: ${reservation.gender}<br>  
Meals:   
<ul>  
<c:forEach var="meal" items="${reservation.food}">  
<li>${meal}</li>  
</c:forEach>  
</ul>  
Leaving From : ${reservation.cityFrom} <br>  
Going To : ${reservation.cityTo}  
</body>  
</html>  

Spring MVC CRUD Example


CRUD( Create, Read, Update and Delete) application is the most important application
for creating any project. It provides an idea to develop a large project. In spring MVC,
we can develop a simple CRUD application.

Here, we are using JdbcTemplate for database interaction.

Create a table
Here, we are using emp99 table present in the MySQL database. It has 4 fields: id, name,
salary, and designation. Here, id is auto incremented which is generated by the
sequence.

Create table emp99(id int primary key auto_increment ,name varchar(20),salary double,
designation varchar(20))

Spring MVC CRUD Example


1. Add dependencies to pom.xml file.
pom.xmlExceptHandling in Java -

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> 
 
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->  
<dependency>  
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <version>8.0.11</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->  
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-jdbc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  

2. Create the bean class


Here, the bean class contains the variables (along setter and getter methods)
corresponding to the fields exist in the database.

Emp.java

package com.java.beans;    
    
public class Emp {    
private int id;    
private String name;    
private float salary;    
private String designation;    
    
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 float getSalary() {    
    return salary;    
}    
public void setSalary(float salary) {    
    this.salary = salary;    
}    
public String getDesignation() {    
    return designation;    
}    
public void setDesignation(String designation) {    
    this.designation = designation;    
}    
    
}    

3. Create the controller class


EmpController.java

package com.java.controllers;     
import java.util.List;    
import org.springframework.beans.factory.annotation.Autowired;    
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
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 com.java.beans.Emp;    
import com.java.dao.EmpDao;    
@Controller    
public class EmpController {    
    @Autowired    
    EmpDao dao;//will inject dao from XML file    
        
    /*It displays a form to input data, here "command" is a reserved request attribu
te  
     *which is used to display object data into form  
     */    
    @RequestMapping("/empform")    
    public String showform(Model m){    
        m.addAttribute("command", new Emp());  
        return "empform";   
    }    
    /*It saves object into database. The @ModelAttribute puts request data  
     *  into model object. You need to mention RequestMethod.POST method   
     *  because default request is GET*/    
    @RequestMapping(value="/save",method = RequestMethod.POST)    
    public String save(@ModelAttribute("emp") Emp emp){    
        dao.save(emp);    
        return "redirect:/viewemp";//will redirect to viewemp request mapping    
    }    
    /* It provides list of employees in model object */    
    @RequestMapping("/viewemp")    
    public String viewemp(Model m){    
        List<Emp> list=dao.getEmployees();    
        m.addAttribute("list",list);  
        return "viewemp";    
    }    
    /* It displays object data into form for the given id.   
     * The @PathVariable puts URL data into variable.*/    
    @RequestMapping(value="/editemp/{id}")    
    public String edit(@PathVariable int id, Model m){    
        Emp emp=dao.getEmpById(id);    
        m.addAttribute("command",emp);  
        return "empeditform";    
    }    
    /* It updates model object. */    
    @RequestMapping(value="/editsave",method = RequestMethod.POST)    
    public String editsave(@ModelAttribute("emp") Emp emp){    
        dao.update(emp);    
        return "redirect:/viewemp";    
    }    
    /* It deletes record for the given id in URL and redirects to /viewemp */    
    @RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)    
    public String delete(@PathVariable int id){    
        dao.delete(id);    
        return "redirect:/viewemp";    
    }     
}  

4. Create the DAO class


Let's create a DAO class to access the required data from the database.

EmpDao.java

package com.java.dao;    
import java.sql.ResultSet;    
import java.sql.SQLException;    
import java.util.List;    
import org.springframework.jdbc.core.BeanPropertyRowMapper;    
import org.springframework.jdbc.core.JdbcTemplate;    
import org.springframework.jdbc.core.RowMapper;    
import com.java.beans.Emp;    
    
public class EmpDao {    
JdbcTemplate template;    
    
public void setTemplate(JdbcTemplate template) {    
    this.template = template;    
}    
public int save(Emp p){    
    String sql="insert into Emp99(name,salary,designation) values('"+p.getName()
+"',"+p.getSalary()+",'"+p.getDesignation()+"')";    
    return template.update(sql);    
}    
public int update(Emp p){    
    String sql="update Emp99 set name='"+p.getName()+"', salary=
"+p.getSalary()+",designation='"+p.getDesignation()+"' where id="+p.getId()+"";  
  
    return template.update(sql);    
}    
public int delete(int id){    
    String sql="delete from Emp99 where id="+id+"";    
    return template.update(sql);    
}    
public Emp getEmpById(int id){    
    String sql="select * from Emp99 where id=?";    
    return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowM
apper<Emp>(Emp.class));    
}    
public List<Emp> getEmployees(){    
    return template.query("select * from Emp99",new RowMapper<Emp>(){    
        public Emp mapRow(ResultSet rs, int row) throws SQLException {    
            Emp e=new Emp();    
            e.setId(rs.getInt(1));    
            e.setName(rs.getString(2));    
            e.setSalary(rs.getFloat(3));    
            e.setDesignation(rs.getString(4));    
            return e;    
        }    
    });    
}    
}   

5. Provide the entry of controller in the web.xml file


web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

6. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
<context:component-scan base-package="com.java.controllers"></
context:component-scan>    
    
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolv
er">    
<property name="prefix" value="/WEB-INF/jsp/"></property>    
<property name="suffix" value=".jsp"></property>    
</bean>    
    
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataS
ource">    
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></
property>    
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>    
<property name="username" value=""></property>    
<property name="password" value=""></property>    
</bean>    
    
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">    
<property name="dataSource" ref="ds"></property>    
</bean>    
    
<bean id="dao" class="com.java.dao.EmpDao">    
<property name="template" ref="jt"></property>    
</bean>       
</beans>  

7. Create the requested page


index.jsp

<a href="empform">Add Employee</a>  
<a href="viewemp">View Employees</a>  

8. Create the other view components


empform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>   
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
  
        <h1>Add New Employee</h1>  
       <form:form method="post" action="save">    
        <table >    
         <tr>    
          <td>Name : </td>   
          <td><form:input path="name"  /></td>  
         </tr>    
         <tr>    
          <td>Salary :</td>    
          <td><form:input path="salary" /></td>  
         </tr>   
         <tr>    
          <td>Designation :</td>    
          <td><form:input path="designation" /></td>  
         </tr>   
         <tr>    
          <td> </td>    
          <td><input type="submit" value="Save" /></td>    
         </tr>    
        </table>    
       </form:form>    

empeditform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>   
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
  
       <h1>Edit Employee</h1>  
    <form:form method="POST" action="/SpringMVCCRUDSimple/editsave">    
        <table >    
        <tr>  
        <td></td>    
         <td><form:hidden  path="id" /></td>  
         </tr>   
         <tr>    
          <td>Name : </td>   
          <td><form:input path="name"  /></td>  
         </tr>    
         <tr>    
          <td>Salary :</td>    
          <td><form:input path="salary" /></td>  
         </tr>   
         <tr>    
          <td>Designation :</td>    
          <td><form:input path="designation" /></td>  
         </tr>   
           
         <tr>    
          <td> </td>    
          <td><input type="submit" value="Edit Save" /></td>    
         </tr>    
        </table>    
       </form:form>    

viewemp.jsp

   <%@ taglib uri="http://www.springframework.org/tags/form" prefi
x="form"%>    
   <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
  
<h1>Employees List</h1>  
<table border="2" width="70%" cellpadding="2">  
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</
th><th>Edit</th><th>Delete</th></tr>  
   <c:forEach var="emp" items="${list}">   
   <tr>  
   <td>${emp.id}</td>  
   <td>${emp.name}</td>  
   <td>${emp.salary}</td>  
   <td>${emp.designation}</td>  
   <td><a href="editemp/${emp.id}">Edit</a></td>  
   <td><a href="deleteemp/${emp.id}">Delete</a></td>  
   </tr>  
   </c:forEach>  
   </table>  
   <br/>  
   <a href="empform">Add New Employee</a>  

Spring MVC Validation


The Spring MVC Validation is used to restrict the input provided by the user. To validate
the user's input, the Spring 4 or higher version supports and use Bean Validation API. It
can validate both server-side as well as client-side applications.

Bean Validation API


The Bean Validation API is a Java specification which is used to apply constraints on
object model via annotations. Here, we can validate a length, number, regular
expression, etc. Apart from that, we can also provide custom validations.

As Bean Validation API is just a specification, it requires an implementation. So, for that,
it uses Hibernate Validator. The Hibernate Validator is a fully compliant JSR-303/309
implementation that allows to express and validate application constraints.

Validation Annotations

Annotation Description

@NotNull It determines that the value can't be null.

@Min It determines that the number must be equal or greater than the specified value.
@Max It determines that the number must be equal or less than the specified value.

@Size It determines that the size must be equal to the specified value.

@Pattern It determines that the sequence follows the specified regular expression.

Spring MVC Validation Example


In this example, we create a simple form that contains the input fields. Here, (*) means it
is mandatory to enter the corresponding field. Otherwise, the form generates an error.

Add dependencies to pom.xml file.


pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> 
 
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
 <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-
validator -->  
<dependency>  
    <groupId>org.hibernate.validator</groupId>  
    <artifactId>hibernate-validator</artifactId>  
    <version>6.0.13.Final</version>  
</dependency>  

2. Create the bean class


Employee.java

package com.java;  
import javax.validation.constraints.Size;  
  
public class Employee {  
  
    private String name;  
    @Size(min=1,message="required")  
    private String pass;  
      
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getPass() {  
        return pass;  
    }  
    public void setPass(String pass) {  
        this.pass = pass;  
    }     
}  

3. Create the controller class


In controller class:

o The @Valid annotation applies validation rules on the provided object.


o The BindingResult interface contains the result of validation.

package com.java;  
  
import javax.validation.Valid;  
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;  
  
@Controller  
public class EmployeeController {  
  
    @RequestMapping("/hello")  
    public String display(Model m)  
    {  
        m.addAttribute("emp", new Employee());  
        return "viewpage";  
    }  
    @RequestMapping("/helloagain")  
    public String submitForm( @Valid @ModelAttribute("emp") Employee e, Bindi
ngResult br)  
    {  
        if(br.hasErrors())  
        {  
            return "viewpage";  
        }  
        else  
        {  
        return "final";  
        }  
    }  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
    <!-- Define Spring MVC view resolver -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>       
     </bean>  
</beans>  

6. Create the requested page


index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<html>  
<body>  
<a href="hello">Click here...</a>  
</body>  
</html>  
7. Create the other view components
viewpage.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<html>  
<head>  
<style>  
.error{color:red}  
</style>  
</head>  
<body>  
<form:form action="helloagain" modelAttribute="emp">  
Username: <form:input path="name"/> <br><br>  
Password(*): <form:password path="pass"/>    
<form:errors path="pass" cssClass="error"/><br><br>  
<input type="submit" value="submit">  
</form:form>  
</body>  
</html>  

final.jsp

<html>  
<body>  
Username: ${emp.name} <br><br>  
Password: ${emp.pass}  
</body>  
</html>  

Spring MVC Number Validation


In Spring MVC Validation, we can validate the user's input within a number range. The
following annotations are used to achieve number validation:
o @Min annotation - It is required to pass an integer value with @Min annotation.
The user input must be equal to or greater than this value.
o @Max annotation - It is required to pass an integer value with @Max
annotation. The user input must be equal to or smaller than this value.

Spring MVC Number Validation Example


1. Add dependencies to pom.xml file.
pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> 
 
<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>5.1.1.RELEASE</version>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->  
<dependency>  
    <groupId>org.apache.tomcat</groupId>  
    <artifactId>tomcat-jasper</artifactId>  
    <version>9.0.12</version>  
</dependency>  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->  
<dependency>    
    <groupId>javax.servlet</groupId>    
    <artifactId>servlet-api</artifactId>    
    <version>3.0-alpha-1</version>    
</dependency>  
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>jstl</artifactId>  
    <version>1.2</version>  
</dependency>  
 <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-
validator -->  
<dependency>  
    <groupId>org.hibernate.validator</groupId>  
    <artifactId>hibernate-validator</artifactId>  
    <version>6.0.13.Final</version>  
</dependency>  

2. Create the bean class


Employee.java

package com.java;  
  
import javax.validation.constraints.Max;  
import javax.validation.constraints.Min;  
import javax.validation.constraints.Size;  
  
public class Employee {  
  
    private String name;  
    @Size(min=1,message="required")  
    private String pass;  
      
    @Min(value=18, message="must be equal or greater than 18")  
    @Max(value=45, message="must be equal or less than 45")  
    private int age;  
      
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getPass() {  
        return pass;  
    }  
    public void setPass(String pass) {  
        this.pass = pass;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
      
}  

3. Create the controller class


EmployeeController.java

package com.java;  
  
import javax.validation.Valid;  
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;  
  
@Controller  
public class EmployeeController {  
  
    @RequestMapping("/hello")  
    public String display(Model m)  
    {  
        m.addAttribute("emp", new Employee());  
        return "viewpage";  
    }  
    @RequestMapping("/helloagain")  
    public String submitForm( @Valid @ModelAttribute("emp") Employee e, Bindi
ngResult br)  
    {  
        if(br.hasErrors())  
        {  
            return "viewpage";  
        }  
        else  
        {  
        return "final";  
        }  
    }  
}  

4. Provide the entry of controller in the web.xml file


web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">  
  <display-name>SpringMVC</display-name>  
   <servlet>    
    <servlet-name>spring</servlet-name>    
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>    
    <load-on-startup>1</load-on-startup>      
</servlet>    
<servlet-mapping>    
    <servlet-name>spring</servlet-name>    
    <url-pattern>/</url-pattern>    
</servlet-mapping>    
</web-app>  

5. Define the bean in the xml file


spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
    <!-- Provide support for component scanning -->  
    <context:component-scan base-package="com.java" />  
    <!--Provide support for conversion, formatting and validation -->  
    <mvc:annotation-driven/>  
    <!-- Define Spring MVC view resolver -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.Interna
lResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>       
     </bean>  
</beans>  

6. Create the requested page


index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<html>  
<body>  
<a href="hello">Click here...</a>  
</body>  
</html>  

7. Create the other view components


viewpage.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  
<html>  
<head>  
<style>  
.error{color:red}  
</style>  
</head>  
<body>  
<form:form action="helloagain" modelAttribute="emp">  
Username: <form:input path="name"/> <br><br>  
Password: <form:password path="pass"/>    
<form:errors path="pass" cssClass="error"/><br><br>  
Age: <form:input path="age"/>   
<form:errors path="age" cssClass="error"/><br><br>  
<input type="submit" value="submit">  
</form:form>  
</body>  
</html>  

final.jsp

<html>  
<body>  
Username: ${param.name} <br>  
Password: ${param.pass} <br>  
Age: ${param.age } <br>  
</body>  
</html>  

You might also like