Nearby lessons

18 of 35

Spring - Web MVC Framework

📌 What You Will Learn
  • Understand Spring - Web MVC Framework
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Web MVC Framework step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Web MVC Framework

  • Spring Web MVC is providing very good Data Binding Mechanisms, Data Validations ... for

web applications.

  • Spring Web MVC is providing Customizable handler mapping and view resolution.
  • Spring Web MVC module is more Flexible model transfer. Model transfer with a

name/value Map supports easy integration with any view technology.

  • Spring Web MVC provides customizable locale and theme resolution, support for JSPs with

or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, and so on.

  • Spring Web MVC allows all JSP supported Tag Libraries like JSTL tag libraries,...

Spring Web MVC Components

To prepare Spring Web MVC Applications we have to use the following Components.

  • View
  • web.xml
  • DispatcherServlet
  • HandlerMapping
  • Controller Component
  • Command Class
  • View Resolver
  • Spring Configuration File

From the above diagram,

  • Submitting request from Client to Servler Side web application, where DispatcherServlet will recieve request.
  • DispatcherServlet will interact with HandlerMapping to get Controller name and location.
  • HandlerMapping will return the name and location of the Controller class.
  • DispatcherServlet will recognize the name and location of the Controller class and

perform loading and instantiation of yje Controller class.

  • Depending on the Controller, Form data will be stored in Command Object and that

Command object data will be used in Controller class.

  • After executing Business logic, Controller class will return ModelAndView object, which

contains logical name of the view in View object and Model object is a Map contains Model Objects inorder to use that data in View part.

  • DispatcherServlet will interact with ViewResolver inorder to get the name and location of the View page.
  • ViewResolver will return View object with the name and location of the View page.
  • DispatcherServlet will interact witj View part with Model part inorder to prepare response.
  • View part will prepare response and submitting that response to DispatcherServlet.
  • DispatcherServlet will generate the required response to Client.

View

Q)What is the requirement to use View part in Web applications?

Ans

  • It will improve Look And Feel to the web applications. to
  • It will provid entry point for the users inorder to interact with applications. using
  • It will provide very good environment to take data from users inorder to submit data

the server side application.

  • It able to provide very good environment to perform Client Side data validations by

Java Script functions.

  • It allows to specify different types of requests like GET, POST, HEAD,... to the web

applications.

There are two types of View parts are existed. data to the

Informational View

 It able to display messages to the users, status of the server side actions.  It will not include forms, it will not take data from Users, simply it will display

users.

Form Based View

 It will include forms to take data from users and to submit that data to the Users.

To prepare View part, we will use View based Tech like AWT, SWING, JAVA FX, html, Jsp, velocity, freemarker,......

Spring Framework is able to allow all the advanced view tech ,but, at basic level, We will use JSP tech with Spring provided tag library.

web.xml[Deployment Descriptor]

web.xml is deployment descriptor, it will provide metadata about the web application which is required by the container inorder to identify the server side components and inorder to execute server side components.

In web applicatins, web.xml file is responsible for

  • welcome files configuration
  • Context parameters conf.
  • Servlets Conf.
  • Filters Conf.
  • Listeners Conf.
  • Session time out conf.
  • Error Pages Conf.
  • Tag Libraries conf.
  • Security conf....

In Spring web MVC applicatins , web.xml file requirement is to configure Font Controller that is DispatcherServlet inorder to activate FrontController by Web containers.

In Spring Framework, DispatcherServlet is FrontControiller provided by Spring Framework in the form of "org.springframework.web.servlet.DispatcherServlet".

In DispatcherServlet conf, we will provide the following configuration details

a)DispatcherServlet class conf.

  • Logical name of the Dispatcher Servlet conf.
  • DispatcherServlet class conf.
  • Initialization Parameters conf.
  • Load on Startup Configuration.

b)URL Mapping Def. Where DispatcherServlet must have logical name , on the basis of this logical name only we will prepare Spring configuration file name, that is, logical_Name-servlet.xml

EX: <servlet-name>dispatcherServlet</servlet-name>

Note: in the above case, Spring configuration file name must be

dispatcherServlet-Servlet.xml

Where DispatcherServlet class must be configured with its fully qualified name inorder to activate FrontController. EX: <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> Where Initialization Parameters are required to create Framework related objects like Handlermapping, HandlerAdapter, ViewResolver,.....

Note: The default name and location of Spring configuration file is under WEB-INF folder with the name "Servlet_Logical_Name-servlet.xml", but, if we want to change this name and location then we must use "contextConfigLocation" initialization parameter in DispatcherServlet configuration.

Example10
JCode Cell
1 
2<init-param>
3<param-name>contextConfigLocation</param-name>
4<param-value>/WEB-INF/configd/myconfig.xml</param-value>
5</init-param>
6

dispatcherServlet-Servlet.xml — web.xml

Where load-on-startup configuration is required inorder to perform DispatcherServlet loading, instantiation and initialization at the time of server startup, where DispatcherServlet innitialization is required to load the complete Spring web MVC famework.

EX: <load-on-startup>1</load-on-startup>

Where URL pattern definition is required for each and every Servlet in web applications. IN general, in web applications, we will define URL patterns for the Servlets in the following three approaches.

  • Exact Match Method
  • Directory Match Method
  • Extension Match Method

From the above Url pattern definitions, DispatcherServlet required to use either Directory Match method[/*] or Extension Match Method[*.do] inorder to trap all the requests from Clients to DispatcherServlet.

Example11
JCode Cell
1 
2<web-app>
3<servlet>
4<servlet-name>dispatcherServlet</servlet-name>
5<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
6<load-on-startup>1</load-on-startup>
7</servlet>
8<servlet-mapping>
9<servlet-name>dispatcherServlet</servlet-name>
10<url-pattern>*.do</url-pattern> or
11<url-pattern>/*</url-pattern>
12</servlet-mapping>
13</web-app>
14

DispatcherServlet

The main intention of the Front Controller in web applications is ,

  • Getting request from clients
  • Identifying the respective Model component or Business component which includes

business logic.

  • Executing Business Logic which is existed in Business component.
  • Identifying the respective View part inorder to generate response.
  • Forwarding request to view part inorder to generate dynamic response.

In Spring web mvc module , DispatcherServlet is acting as the Front Controller provided by Spring Framework in the form of "org.springframework.web.servlet.DispatcherServlet". Spring Framework has provided DispatcherServlet with the following Structer.

 Where HttpServletBean is the first Spring-aware class in the hierarchy. It injects the bean‘s properties using the servlet init-param values received from the web.xml or from WebApplicationInitializer.

 Where FrameworkServlet integrates the Servlet functionality with a web application context, implementing the ApplicationContextAware interface. But it is also able to create a web application context on its own.  Where DispatcherServlet will perform the following actions in Spring web MVC applications inorde to process the requests.

From the above diagram,

  • When we start server, container will perform the following actions.
  • Container will recognize all the web applications which are existed under webapps folder.
  • Container will deploy all the web applications under server space.
  • Container will create a separate ServletContext object for each and every web application

which we deployed.

  • While deploying web application, container will perform the following actions,
  • Container will recognize web.xml file under WEB-INF folder.
  • Container will perform web.xml file loading, parsing and reading the content from web.xml

file.

  • While parsing web.xml file, Container will recognize load-on-startup configuration under

DispatcherServlet configuration.

  • With the load-on-startup configuration, Container will search for DispatcherServlet under

classes folder, if it is not existed then container will search for DispatcherServlet under web application lib folder.

  • When DispatcherServlet identifies then container will perform DispatcherServlet loading, instantiation and initialization at the time of server startup or at the time of web application deployment.
  • As part of DispatcherServlet initialization, DispatcherServlet will perform the following actions.
  • DispatcherServlet will recognize WebApplicationContext implementation class and perform WebApplicationContext loading, instantiation and initialization.
  • As part of WebApplicationContext initialization, WebApplicationContext will recognize

Struts configuration file under WEB-INF folder with the name [Servlet-Name]- servlet.xmland WebApplicationContext will perform Spring configuration file loading, parsing and reading the content into Configuration object.

  • After getting all the configuration details from spring configuration file into Configuration object, WebApplicationContext container will create bean objects which we configured under spring configuration file.
  • After getting all bean objects, WebApplicationContext will create Framework objects like HandlerMapping, HandlerAdapter, ViewResolver, ThemeResolver, LocaleResolver,…….. as part of WebApplicationContext initialization.
  • When we submit request from client to Server then Protocol will take request and perform the following actions.
  • Protocol will establish connection between client and server on the basis of the Server IP Address and Port number.
  • Protocol will create request format contains Header part and Body part, where Header part is able to manage Clients metadata and Body part is able to manage Request parameters data which are provided by the user at client browser.
  • Protocol will carry request format to Server, where Server will forward request to web container.
  • When request is coming to the container then Web Container will take URL pattern value from request format and container is trying to compare the URL pattern of the DispatcherServlet which we configured in web.xml file, where if the url pattern is matched with DispatcherServlet URL pattern then container will forward request to DispatcherServlet.
  • When request is coming to the DispatcherServlet then DispatcherServlet will perform the following actions

 DispathcerServlet will keep all the Framework objects like HandlerMapping, HandlerAdapter, ViewResolver, ThemeResolver, LocaleResolver,…… in request scope in order to make available to the Handler and View part.

 DispatcherServlet will interact with HandlerMapping object to get Handler or Controller object by executing getHandler() method.

 When DispatcherServlet call getHandler() on HandlerMapping object , HandlerMapping will identify the respective Handler object and its configured interceptors then Handler Mapping will arrange all the interceptors before Handler and return HandlerExecutionChain object which contains Handler object and a set of interceptors.

Note: Interceptors are like Filters in servlets, which are used to perform pre-processing and post-processing activities for any web resource.

 After getting HandlerExecutionChain object, DispatcherServlet will use HandlerAdapter object to access Handler by using handle() method, where HandlerAdapter will execute all the interceptors inorder to perfrom pre-processing activities by calling preHandle() method.

 After executing all the interceptors, HandlerAdpter will access business logic which is included in Handler or Controller component.

 By the execution of Business login in Handler class, Handler will return ModelAndView object to HandlerAdapter by executing all the interceptors in reverse inorder to provide post-processing activities by executing postHandle() method, where HandlerAdapter will send the received ModelAndView object to DispatcherServlet.

Note: Where ModelAndView object contains View objct and Model object, where View object contains view name inorder to identify view part and Model object contains no of Objects to provide data to the View part.

 After getting ModelAndView object, DispatcherServlet will interact with ViewResolver inordee to identify view JSP page url on the basis of View name.

 When View is identified in web application then DispatcherServlet will execute the corresponsing view page by getting data from Model part a and DispatcherServlet will prepare Response for the client.

 When DispatcherServlet prepares response , DispatcherServlet will send response to client, where Protocol will take that response and protocol will perform the following actions.

a) Protocol will prepare response format contains Header part and Body part, where Header part is able to manage response headers data like response size, type of response,….. and Body part is able to manage the actual dynamic response.

b) Protocol will carry response format to client, where client browser will display the generated response.

c) When response is generated at client browser , protocol will destroy the connection which is established between client and Server.

d) When we shutdown the server or when we undeploy the web application then container will perform DispatcherServlet deinstantiation, with this, all the Spring Framework objects like HandlerMapping, HandlerAdapter, viewResolver,….. are destroyed.

HandlerMapping

The main intention of HandlerMapping is to map incoming request to the Handler class that can handle requests. When request is coming to DispathcerServlet, DispatcherServlet will forward request to HandlerMapping , where HandlerMapping will identify the respective Handler class and its associated interceptors then HandlerMapping will create HandlerExecutionChain with Handler class object and and interceptors stack and return HandlerExecutinChain to DispatcherServlet. Spring Framework has provided the following HandlerMappings inorder to map requests to Handler classes.

  • BeanNameUrlHandlerMapping ii. SimpleUrlHandlerMapping iii. ControllerClassNameHandlerMapping iv. CommonsPathMapHandlerMapping

Note: IN Spring web MVC applications, if we want to use the HandlerMapping classes then we must configure them in Spring configuration File.

i. BeanNameUrlHandlerMapping It is default HandlerMapping in Spring applications, it will be used by Spring framework when no HandlerMapping is configured in Spring configuration file. This HandlerMapping map URLs to beans with names that start with a slash ("/"), similar to how Struts maps URLs to action names. Spring Framework has provided this Handler mapping like “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”.

Example14
JCode Cell
1 
2<beans>
3-----
4<bean name=‖/welcome.htm‖ class=‖com.durgasoft.controller.WelcomeController‖/>
5<bean name=‖/hello.htm‖ class=‖com.durgasoft.controller.HelloController‖/>
6<bean name=‖handlerMapping‖ class=‖org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping‖/>
7------
8</beans>
9

HandlerMapping

 In the above configuration, if we submit request with the url http://localhost:1010/app/welcome.htm then BeanUrlHandlermapping will forward request to WelcomeController .

 In the above configuration, if we submit request with the url http://localhost:1010/app/hello.htm then BeanUrlHandlermapping will forward request to HelloController .

ii. SimpleUrlHandlerMapping

This HandlerMapping is able to map Handler or Controller classes by matching URL path with the property key of the properties . Spring Framework has provided this HandlerMapping like “org.springframework.web.servlet.handler.SimpleUrlHandlermapping”.

Example16
JCode Cell
1 
2<beans>
3------
4<bean name=‖addEmp‖ class=‖com.durgasoft.controller.AddEmployeeController‖/>
5<bean name=‖searchEmp‖ class=‖com.durgasoft.controller.SearchEmployeeController‖/>
6<bean name=‖deleteEmp‖ class=‖com.durgasoft.controller.DeleteEmployeeController‖/>
7<bean name=‖handlerMapping‖ class=―org.springframework.web.servlet.handler.SimpleUrlHandlermapping‖>
8 <property name=‖mappings‖>
9 <props>
10 <prop key=‖addEmployee.htm‖>addEmp</prop>
11 <prop key=‖searchEmployee.htm‖>searchEmp</prop>
12 <prop key=‖deleteEmployee.htm‖>deleteEmp</prop>
13 </props>
14 </property>
15</bean>
16</beans>
17

ii. SimpleUrlHandlerMapping

 If we submit request like http://localhost:1010/app/addEmployee.htm then SimpleUrlHandlerMapping will forward request to AddEmployeeController class.

 If we submit request like http://localhost:1010/app/searchEmployee.htm then SimpleUrlHandlerMapping will forward request to SearchEmployeeController class.

 If we submit request like http://localhost:1010/app/deleteEmployee.htm then SimpleUrlHandlerMapping will forward request to DeleteEmployeeController class.

iii. ControllerClassNameHandlerMapping

This HandlerMapping follows a simple convention for generating URL path mappings from the class names of registered Controller beans as well as @Controller annotated beans. For simple Controller implementations (those that handle a single request type), the convention is to take the short name of the Class, remove the 'Controller' suffix if it exists and return the

remaining text, lower-cased, as the mapping, with a leading /. For example

Spring Framework has provided this HandlerMapping like “org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping”.

Example19
JCode Cell
1 
2<beans>
3------
4<bean id=‖welcome‖ class=‖com.durgasoft.controller.WelcomeController‖/>
5<bean name=‖hello‖ class=‖com.durgasoft.controller.HelloController‖/>
6<bean name=‖handlerMapping‖ class=―org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping‖/>
7 
8 
9</beans>
10

remaining text, lower-cased, as the mapping, with a leading /. For example

 If we submit request like http://localhost:1010/app/welcome* then BeanClassNameHandlerMapping will access WelcomeController class.

 If we submit request like http://localhost:1010/app/hello* then BeanClassNameHandlerMapping

iv. CommonsPathMapHandlerMapping The org.springframework.web.servlet.handler.CommonsPathMapHandlerMapping is one of the implementation of HandlerMapping interface.

The org.springframework.web.servlet.handler.CommonsPathMapHandlerMapping is designed to recognize Commons attributes meta data attributes of type PathMap defined in the application controller and automatically wires them in to the current DiapatcherServlet's Web-application context.

To use this HandlerMapping the controller class must have a class level metadata of the form @org.springframework.web.servlet.handler.commonsattribures.PathMap("/mypath.spring"). We can configure multiple path maps for a single controller.

Example20
JCode Cell
1 
2@org.springframework.web.servlet.handler.commonsattribures.PathMap(
3 "/mypath.spring")
4 
5public class FirstController implements Controller {
6 
7public ModelAndView handleRequest(HttpServletRequest request,
8 HttpServletResponse response)throws Exception {
9System.out.println("we are in handleRequest()");
10ModelAndView mav=null;
11return mav;
12}
13 
14

Controller Component

The main intention of Controller in Spring web MVC is to manage application logic or to have controller logic to manage Service layer provided business methods access. To prepare Controller classes in Spring web MVC applications Spring framework has provided the following predefined Library.

All the above Controller classes are the implementation of org.springframework.web.servlet.mvc.Controller interface. org.springframework.web.servlet.mvc.Controller interface has provided the following method to include business logic or controller component logic. Public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp)throws Exception In Spring web MVC application we can prepare Controller class either by implementing Controller interface or by extending the above Controller classes.

Example21
JCode Cell
1 
2Public class LoginController implements Controller{
3Public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)throws Exception{
4 ------------
5return new ModelAndView(―success‖);
6}
7

Controller Component

Where ModelAndView is an object that holds both the model and view. The handler returns the ModelAndView object and DispatcherServlet resolves the view using View Resolvers and View. The View is an object which contains view name in the form of the String and model is a map to add multiple objects. To create ModelAndView object we have to use the following constructors.

  • Public ModelAndView()
  • Public ModelAndView(String view_Name)
  • Public ModelAndView(String view_Name, Map model)
  • Public ModelAndView(String view_Name, HttpStatus status)
  • Public ModelAndView(String view_Name, String model_Name, Object model)

-------- ---------- Note:If we want to use Controller classes in Spriong web MVC applications then we have to configure in Spring configuration File.

Command Class

The main intention of Command class is to store form data which is submitted by the client when we use FormCommandControllers. It is like ActionForm component in Struts framework.

Example23
JCode Cell
1 
2public class User{
3private String uname;
4private String upwd;
5setXXX() and getXXX()
6}
7View Resolver:
8

Command Class

In Spring MVC, view resolvers enable you to render models in a browser without tying you to a specific view technology like JSP, Velocity, XML…etc. There are two interfaces that are important to the way Spring handles views are ViewResolverand View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.

Spring Framework has provided the following ViewResolvers  ViewResolver-View Resolvers get a org.springframework.web.servlet.View based on a

view name.  ContentNegotiatingViewResolver-This is an implementation of a view resolver based on

the request file name or Accept header. This class delegates view resolution to other view resolvers that are configured. The class uses the MediaType from the request to determine a view. The class first determines the MediaType, then asks each ViewResolver to return a view. The class then compares the all returned views‘ content type and the one that is most compatible with the request MediaType is chosen.  BeanNameViewResolver-This resolver implemenatation resolves a view name as a bean name registered in the application context. In other words, the view is registered as a bean and this resolver gets the name of that bean  UrlBasedViewResolver-This directly resolves a view name to a URL without any explicit mapping. The view names can be the URL themselves or a prefix or suffix can be added to get the URL from the view name. To redirect a URL use the ‗redirect:‘ prefix. To forward a URL use the ‗forward:‘ prefix.  InternalResourceViewResolver-This is a subclass of UrlBasedViewResolver and supports an InternalResourceView. An InternalResourceView is a wrapper for JSP or some other resource that reside in the same web application. It exposes the model objects as request attributes. If JSTL API is present then the resolver resolves the view name to a JSTLView. An InternalResourceViewResolver needs to be last, if a chain of view resolvers is used, since this resolves the view name irrespective of whether the actual resource is present or not.  FreeMarkerViewResolver-This is a subclass of UrlBasedViewResolver that supports FreeMarkerView and its subclasses. The View Class generated can be specified by the ‗viewClass‘ property.  VelocityViewResolver-This is a subclass of UrlBasedViewResolver that supports VelocityView and its subclasses.  JasperReportsViewResolver-Supports AbstractJasperReportsView by resolving the view name to the URL of the report file.  XsltViewResolver– Supports XsltView by resolving the view name to the URL of the XSLT Stylesheet.

IN spring Web MVC applications we have to configure view Resolver in Spring configuration file with the name ―viewResolver‖ id name.

Example24
JCode Cell
1 
2<bean id=‖viewResolver‖ class=‖org.springframework.web.servlet.view.InternalResourceViewResolver‖>
3<property name=‖prefix‖ value=‖WEB-INF‖/>
4<property name=‖suffix‖ value=‖.jsp‖/>
5</bean>
6Spring Configuration File.
7

Command Class

In Spring web MVC application, Spring configuration file is recognized by WebApplicationContext container with the name [DS_Logical_Name]-servlet.xml under WEB-INF folder. The main intention of Spring configuration file in Spring Web MVC application is to provide the configuration details like,

  • Controller classes and their dependencies configuration
  • HandlerMapping configuration.
  • ViewResolver Configuration
Example25
JCode Cell
1 
2<beans>
3-----
4<bean name=‖/welcome.htm‖ class=‖com.durgasoft.controller.WelcomeController‖/>
5<bean name=‖/hello.htm‖ class=‖com.durgasoft.controller.HelloController‖/>
6<bean name=‖handlerMapping‖ class=‖org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping‖/>
7<bean id=‖viewResolver‖ class=‖org.springframework.web.servlet.view.InternalResourceViewResolver‖>
8<property name=‖prefix‖ value=‖WEB-INF‖/>
9<property name=‖suffix‖ value=‖.jsp‖/>
10</bean>
11-------
12</beans>
13

Steps to prepare Spring web MVC Application

  • Create Dynamic web project with all spring JAR files in lib folder.
  • Pepare user forms as per the requirement.
  • Prepare Controller component and Command classes as per the requirement.
  • Prepare Spring configuration File
  • Create or Edit web.xml file with DispatcherServlet Configuration File.

Examples:

app1 — wish.jsp

app1 |---index.jsp |---src | |-----com.durgasoft.controllers.WishController.java |---WEB-INF

|-----web.xml |-----ds-servlet.xml |-----wish.jsp |-----classes

|----com.durgasoft.controllers.WishController.class

Example27
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@page isELIgnored="false" %>
5<!DOCTYPE html>
6<html>
7<head>
8<meta charset="ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body>
12<h1>
13Hello User!, ${message} .
14</h1>
15</body>
16</html>
17

app1 — WishController.java

Example28
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6import org.springframework.web.servlet.ModelAndView;
7import org.springframework.web.servlet.mvc.Controller;
8 
9public class WishController implements Controller {
10 
11@Override
12public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
13ModelAndView mav = new ModelAndView("wish","message", "Welcome to Spring WEB MVC World");
14return mav;
15}
16 
17}
18

app1 — ds-servlet.xml

Example29
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/wish.ds" class="com.durgasoft.controllers.WishController"/>
14<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
15<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16<property name="prefix" value="/WEB-INF/"/>
17<property name="suffix" value=".jsp"/>
18</bean>
19</beans>
20

app1 — web.xml

Example30
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app1</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>*.ds</url-pattern>
21</servlet-mapping>
22</web-app>
23

app1 — index.jsp

Application-2

Example31
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<center>
12<br><br>
13<h3>
14<a href="http://localhost:1010/app2/hello">hello</a>
15<br><br>
16<a href="http://localhost:1010/app2/welcome">welcome</a>
17</h3>
18</center>
19</body>
20</html>
21

app1 — hello.jsp

Example32
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h1>
12Hello User!, This is Spring WEB MVC.
13</h1>
14</body>
15</html>
16

app1 — welcome.jsp

Example33
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h1>Welcome User!, This is Spring WEB MVC.</h1>
12</body>
13</html>
14

app1 — HelloController.java

Example34
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8import org.springframework.web.servlet.mvc.Controller;
9 
10public class HelloController implements Controller {
11 
12@Override
13public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
14ModelAndView mav = new ModelAndView("hello");
15return mav;
16}
17 
18}
19

app1 — WelcomeController.java

Example35
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8import org.springframework.web.servlet.mvc.Controller;
9 
10public class WelcomeController implements Controller {
11 
12@Override
13public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
14 
15ModelAndView mav = new ModelAndView("welcome");
16return mav;
17}
18}
19

app1 — ds-servlet.xml

Example36
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/hello" class="com.durgasoft.controllers.HelloController"/>
14<bean name="/welcome" class="com.durgasoft.controllers.WelcomeController"/>
15 
16<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
17 
18<bean name="viewResolver" class=" org.springframework.web.servlet.view.InternalResourceViewResolver">
19 <property name="prefix" value="/WEB-INF/"/>
20 <property name="suffix" value=".jsp"/>
21</bean>
22</beans>
23

app1 — web.xml

Example37
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app2</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

app1 — index.jsp

Application-3

Example38
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="hellopage"/>
12</body>
13</html>
14

app1 — helloform.html

Example39
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2>Durga Software Solutions</h2>
12<h3>User Hello Form</h3>
13<form action="wish">
14<table>
15<tr>
16<td>User Name</td>
17<td><input type="text" name="uname"/></td>
18</tr>
19<tr>
20<td><input type="submit" value="SayHello"/></td>
21</tr>
22</table>
23</form>
24</body>
25</html>
26

app1 — wish.jsp

Example40
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@page isELIgnored="false" %>
5<!DOCTYPE html>
6<html>
7<head>
8<meta charset="ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body>
12<h1>
13Hello ${name}!
14</h1>
15</body>
16</html>
17

app1 — HelloPageController.java

Example41
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8 
9import org.springframework.web.servlet.mvc.Controller;
10 
11 
12public class HelloPageController implements Controller {
13 
14@Override
15public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
16 
17ModelAndView mav = new ModelAndView("helloform");
18return mav;
19}
20 
21}
22

app1 — WishController.java

Example42
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8import org.springframework.web.servlet.mvc.Controller;
9 
10public class WishController implements Controller {
11 
12@Override
13public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
14ModelAndView mav = new ModelAndView("wish", "name", request.getParameter("uname"));
15return mav;
16}
17}
18

app1 — ds-servlet.xml

Example43
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/hellopage" class="com.durgasoft.controllers.HelloPageController"/>
14<bean name="/wish" class="com.durgasoft.controllers.WishController"/>
15 
16<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
17 
18<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19<property name="prefix" value="/WEB-INF/"/>
20<?xml version="1.0" encoding="UTF-8"?>
21<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
22<display-name>app3</display-name>
23 
24<servlet>
25<servlet-name>ds</servlet-name>
26<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27<load-on-startup>1</load-on-startup>
28</servlet>
29<servlet-mapping>
30<servlet-name>ds</servlet-name>
31<url-pattern>/</url-pattern>
32</servlet-mapping>
33</web-app>
34 
35</bean>
36</beans>
37

app1 — web.xml

Example44
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app3</display-name>
5 
6<servlet>
7<servlet-name>ds</servlet-name>
8<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
9<load-on-startup>1</load-on-startup>
10</servlet>
11<servlet-mapping>
12<servlet-name>ds</servlet-name>
13<url-pattern>/</url-pattern>
14</servlet-mapping>
15</web-app>
16

Application-4 — index.jsp

Example45
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="loginpage"/>
12 </body>
13</html>
14

Application-4 — loginform.jsp

Example46
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2>Durga Software Solutions</h2>
12<h3>User Login Page</h3>
13<form method="POST" action="login">
14<table>
15<tr>
16<td>User Name</td>
17<td><input type="text" name="uname"/></td>
18</tr>
19<tr>
20<td>Password</td>
21<td><input type="password" name="upwd"/></td>
22</tr>
23<tr>
24<td><input type="submit" value="Login"/></td>
25</tr>
26</table>
27</form>
28</body>
29</html>
30

Application-4 — Success.jsp

Example47
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2>Durga Software Solutions</h2>
12<h3>User Login Status</h3>
13<br><br>
14<h1> Login Success</h1>
15</body>
16</html>
17

Application-4 — failure.jsp

Example48
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2>Durga Software Solutions</h2>
12<h3>User Login Status</h3>
13<br><br>
14<h1> Login Failure</h1>
15</body>
16</html>
17

Application-4 — LoginPageController.java

Example49
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8import org.springframework.web.servlet.mvc.Controller;
9 
10public class LoginPageController implements Controller {
11 
12@Override
13public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
14 
15 
16return new ModelAndView("loginform");
17} }
18

Application-4 — LoginController.java

Example50
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.web.servlet.ModelAndView;
8import org.springframework.web.servlet.mvc.Controller;
9 
10public class LoginController implements Controller {
11 
12@Override
13public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
14String uname = request.getParameter("uname");
15String upwd = request.getParameter("upwd");
16ModelAndView mav = null;
17if(uname.equals("durga") && upwd.equals("durga")) {
18 mav = new ModelAndView("success");
19}else {
20 mav = new ModelAndView("failure");
21}
22return mav;
23}
24}
25

Application-4 — ds-servlet.xml

Example51
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/loginpage" class="com.durgasoft.controllers.LoginPageController"/>
14<bean name="/login" class="com.durgasoft.controllers.LoginController"/>
15 
16<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
17 
18<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19<property name="prefix" value="/WEB-INF/"/>
20<property name="suffix" value=".jsp"/>
21</bean>
22</beans>
23

Application-4 — web.xml

Example52
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app4</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

Application-4

Annotations in Spring WEB MVC

Annotations in Spring WEB MVC

Spring Framework has provided annotations support right from its Spring 2.5 version. By using Anotations in SPring Web MVC applications we are able to reduce the following configurations in spring configuation file.

We can remove all Controller classes configuration. We can remove HandlerMapping Class configuration.

Spring Web MVC Frame work has provided the following Annotations mainly.

  • @Controller
  • @RequestMapping
  • @RequestParam
  • @SessionAttributes

@Controller

Before Spring 2.5, all controller classes must be configured in spring configuration file, But, from Spring2.5 version, We are able to declare all controller classes with @Controller annotation to tell the Spring container that this class is a controller.in this context, to give an intemation to the Spring Container about the Controller classes and their locations we have to add the following tag in spring configuration file.

<context:component-scan base-package="package name where controllet classes are existed" />

The above declaration(context:component-scan) tells the Spring container to auto scan the entire package to identify the controller components.

EX:

@Controller public class LoginController { ----- }

  • @RequestMapping

@RequestMapping annotation is used for defining the request urls based on the context root and HTTP request methods like GET , POST, HEAD,... for the request. This Annotation is used as either Class level annotation or Method level Annotation.

Syntax:

@RequestMapping(value="/---" , method=---) Where value member will take Request URL with / prefix. Where method member will take the constants like GET, POST, HEAD,... from RequestMethod enum.

EX:

@Controller public class LoginController {

@RequestMapping(value="/login", method=RequestMethod.POST) public ModelAndView checkLogin(HttpServletRequest request, HttpServletResponse response){

------ return new ModelAndView("success"); } }

Note: It is not mandatory to return ModelAndView object from controller method, where we can return String also but the parameter to Controller Method must be ModelMap, it will take model attributes which we want to submit to View JSP page.

EX:

@Controller public class HelloController {

@RequestMapping(value = "/hello", method = RequestMethod.GET) public String printHello(ModelMap model) {

model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; } }

@RequestParam

@RequestParam annotation will be used in the methods to bind the method parameters to the request parameters. If the request is submitted by the browser, request parameters are passed through the URL query parameters. That can be easily mapped to the methods by annotating the method parameters with @RequestParam.

Syntax:

@RequestParam("paramName")

EX:

@Controller public class LoginController {

@RequestMapping(value="/login", method=RequestMethod.POST) public ModelAndView checkLogin(@RequestParameter("uname") String uname, @RequestParameer("upwd") String upwd){

------ return new ModelAndView("success"); } }

@SessionAttributes — status.jsp

@SessionAttributes is used to define a variable name inorder to keep its Key-Value pair in Session Scope and inorder to use that in multiple pages in the same web application.

Syntax:

@SessionAttributes("Param_Name")

EX:

@Controller @SessionAttributes("status") public class LoginController {

@RequestMapping(value="/login", method=RequestMethod.POST) public ModelAndView checkLogin(@RequestParameter("uname") String uname, @RequestParameer("upwd") String upwd, ModelMap map){

------ map.addAttribute("status", "Login SUCCESS"); return new ModelAndView("success"); } }

Example57
JCode Cell
1 
2<h1>
3<%
4String status = session.getAttribute("status");
5out.println(status);
6%>
7</h1>
8

Example-5 — index.jsp

Example58
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="loginpage"/>
12</body>
13</html>
14

Example-5 — loginform.jsp

Example59
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2>Durga Software Solutions</h2>
12<h3>User Login Page</h3>
13<form method="POST" action="login">
14<table>
15<tr>
16<td>User Name</td>
17<td><input type="text" name="uname"/></td>
18</tr>
19<tr>
20<td>Password</td>
21<td><input type="password" name="upwd"/></td>
22</tr>
23<tr>
24<td><input type="submit" value="Login"/></td>
25</tr>
26</table>
27</form>
28</body>
29</html>
30

Example-5 — status.jsp

Example60
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h1>
12Status : <%= session.getAttribute("status") %>
13</h1>
14<h3>
15<a href="loginpage">|Login Form|</a>
16</h3>
17</body>
18</html>
19

Example-5 — LoginController.java

Example61
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.ui.ModelMap;
8import org.springframework.web.bind.annotation.RequestMapping;
9import org.springframework.web.bind.annotation.RequestParam;
10import org.springframework.web.bind.annotation.SessionAttributes;
11import org.springframework.web.servlet.ModelAndView;
12 
13 
14@org.springframework.stereotype.Controller
15@SessionAttributes("status")
16public class LoginController {
17 
18@RequestMapping("/loginpage")
19public String loginPage(){
20return "loginform";
21}
22 
23 
24@RequestMapping("/login")
25public String login(@RequestParam("uname") String uname, @RequestParam("upwd") String upwd, ModelMap map)throws Exception {
26String status = "";
27if(uname.equals("durga") && upwd.equals("durga")) {
28 map.addAttribute("status", "Login Success");
29}else {
30 map.addAttribute("status", "Login Failure");
31}
32return "status";
33}
34}
35

Example-5 — ds-servlet.java

Example62
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<context:component-scan base-package="com.durgasoft.controllers"/>
14<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
15<property name="prefix" value="/WEB-INF/"/>
16<property name="suffix" value=".jsp"/>
17</bean>
18</beans>
19

Example-5 — web.xml

Example63
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app4</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

Example-5

Spring Web MVC Application with MAVEN

Spring Web MVC Application with MAVEN — index.jsp

  • Create Maven Project
  • Select Archetype: web
  • Update pom.xml
  • Update web.xml
  • Provide all View Resources
  • Provide all Java Resources
  • Provide XML files
  • Run web application
Example65
JCode Cell
1 
2<html>
3<body>
4<jsp:forward page="hellopage"/>
5</body>
6</html>
7

Spring Web MVC Application with MAVEN — helloform.jsp

Example66
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3 pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red">Durga Software Solutions</h2>
12<h3 style="color: blue">User Hello Page</h3>
13<form action="wish">
14<table>
15<tr>
16<td>User Name</td>
17<td><input type="text" name="uname"/></td>
18</tr>
19<tr>
20<td><input type="submit" value="SayHello"/></td>
21</tr>
22</table>
23</form>
24</body>
25</html>
26

Spring Web MVC Application with MAVEN — wish.jsp

Example67
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@page isELIgnored="false" %>
5<!DOCTYPE html>
6<html>
7<head>
8<meta charset="ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body>
12<h1>
13${message}
14</h1>
15<h3>
16<a href="hellopage">|Hello Page|</a>
17</h3>
18</body>
19</html>
20

Spring Web MVC Application with MAVEN — HelloController.java

Example68
JCode Cell
1 
2package com.durgasoft.controllers;
3 
4import org.springframework.stereotype.Controller;
5import org.springframework.ui.ModelMap;
6import org.springframework.web.bind.annotation.RequestMapping;
7import org.springframework.web.bind.annotation.RequestParam;
8 
9@Controller
10public class HelloController {
11@RequestMapping("/hellopage")
12public String helloPage() {
13 
14return "helloform";
15}
16 
17@RequestMapping("/wish")
18public String wish(@RequestParam("uname") String uname, ModelMap map) {
19map.addAttribute("message", "Hello "+uname+"!");
20return "wish";
21} }
22

Spring Web MVC Application with MAVEN — ds-servlet.xml

Example69
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12<context:annotation-config/>
13<context:component-scan base-package="com.durgasoft.controllers"/>
14 
15<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16<property name="prefix" value="/WEB-INF/"/>
17<property name="suffix" value=".jsp"/>
18</bean>
19</beans>
20

Spring Web MVC Application with MAVEN — web.xml

Example70
JCode Cell
1 
2<!DOCTYPE web-app PUBLIC
3"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
4"http://java.sun.com/dtd/web-app_2_3.dtd" >
5 
6<web-app>
7<display-name>Archetype Created Web Application</display-name>
8<servlet>
9<servlet-name>ds</servlet-name>
10<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
11<load-on-startup>1</load-on-startup>
12</servlet>
13<servlet-mapping>
14<servlet-name>ds</servlet-name>
15<url-pattern>/</url-pattern>
16</servlet-mapping>
17</web-app>
18

Spring Web MVC Application with MAVEN — pom.xml

Example71
JCode Cell
1 
2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4<modelVersion>4.0.0</modelVersion>
5<groupId>com.durgasoft</groupId>
6<artifactId>simpleapp</artifactId>
7<packaging>war</packaging>
8<version>0.0.1-SNAPSHOT</version>
9<name>simpleapp Maven Webapp</name>
10<url>http://maven.apache.org</url>
11<dependencies>
12<dependency>
13<groupId>junit</groupId>
14<artifactId>junit</artifactId>
15<version>3.8.1</version>
16<scope>test</scope>
17</dependency>
18 
19<dependency>
20<groupId>javax.servlet</groupId>
21<artifactId>javax.servlet-api</artifactId>
22<version>3.1.0</version>
23<scope>provided</scope>
24</dependency>
25 
26<dependency>
27<groupId>org.springframework</groupId>
28<artifactId>spring-core</artifactId>
29<version>4.3.9.RELEASE</version>
30</dependency>
31 
32 
33<dependency>
34<groupId>org.springframework</groupId>
35<artifactId>spring-context</artifactId>
36<version>4.3.9.RELEASE</version>
37</dependency>
38 
39 
40<dependency>
41<groupId>org.springframework</groupId>
42<artifactId>spring-web</artifactId>
43<version>4.3.9.RELEASE</version>
44</dependency>
45 
46<dependency>
47<groupId>org.springframework</groupId>
48<artifactId>spring-webmvc</artifactId>
49<version>4.3.9.RELEASE</version>
50</dependency>
51 
52</dependencies>
53<build>
54<finalName>simpleapp</finalName>
55<plugins>
56<plugin>
57<groupId>org.apache.maven.plugins</groupId>
58<artifactId>maven-compiler-plugin</artifactId>
59<version>3.8.0</version>
60<configuration>
61 <source>1.8</source>
62 <target>1.8</target>
63</configuration>
64</plugin>
65<plugin>
66<groupId>org.apache.tomcat.maven</groupId>
67<artifactId>tomcat7-maven-plugin</artifactId>
68<version>2.3-SNAPSHOT</version>
69</plugin>
70</plugins>
71</build>
72</project>
73

Controller Classes

The main intention of Controller classes is to manage business logic or to include code inorder access the business logic existed with Business components.

To prepare Controller classes, Spring framework has provided a set of predefined classes in "org.springframework.web.servlet.mvc" package an which are implemented by Controller interface.

AbstractController — index.jsp

This Controller Classe will be used to prepare Controller classes where no form data submission in request, but, it will dispay dynamic content through web pages.

AbstractController class is able to have the following method to have Business logic or the code to access business components.

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)throws Exception

In general, we will use this Controller class in the following situations. When we click on "view profile" link in facebook account, generating profile data When we click on "Get all Jobs" link JOB Portals

----- Note: In all the cases, no form submission is going on, but, dynamic content will be included in response.

Example:

Example73
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="wish"/>
12</body>
13</html>
14

AbstractController — wish.jsp

Example74
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@page isELIgnored="false" %>
5<!DOCTYPE html>
6<html>
7<head>
8<meta charset="ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body>
12<h1 style="color:red">Hello User ${message} </h1>
13</body>
14</html>
15

AbstractController — WishController.java

Example75
JCode Cell
1 
2package com.durgasoft.controller;
3 
4 
5import java.time.LocalTime;
6 
7import javax.servlet.http.HttpServletRequest;
8import javax.servlet.http.HttpServletResponse;
9 
10import org.springframework.web.servlet.ModelAndView;
11import org.springframework.web.servlet.mvc.AbstractController;
12 
13public class WishController extends AbstractController {
14 
15@Override
16protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
17LocalTime time = LocalTime.now();
18int hour = time.getHour();
19String wish_Message = "";
20if(hour<12) {
21 wish_Message = "Good Morning";
22}else if(hour < 17 ){
23 wish_Message = "Good After noon";
24}else {
25 wish_Message = "Good Evening";
26}
27return new ModelAndView("wish", "message", wish_Message);
28}
29}
30

AbstractController — ds-servlet.xml

Example76
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/wish" class="com.durgasoft.controller.WishController"/>
14<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
15<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
16<property name="prefix" value="/WEB-INF/"/>
17<property name="suffix" value=".jsp"/>
18</bean>
19</beans>
20

AbstractController — web.xml

Example77
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<servlet>
5 <servlet-name>ds</servlet-name>
6 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
7 <load-on-startup>1</load-on-startup>
8</servlet>
9<servlet-mapping>
10 <servlet-name>ds</servlet-name>
11<url-pattern>/</url-pattern>
12</servlet-mapping>
13 
14</web-app>
15

AbstractController

There are three types of AbstractControler classes.

  • ParameterizableViewController
  • MultiActionController
  • BaseCommandController

ParameterizableViewController — index.jsp

 Spring framework has provided this controller class in the form of "org.springframework.web.servlet.mvc.ParameterizableViewController".

 The main intention of this controller class is to display web pages with out processing request.

 In ParameterizableViewController classes, it is not required to define any user defined controller class, rather , it must be configured in Spring configuration file directly and it will take "viewName" property with the logical name of the view name inorder to open JSP page.

 IN general, we will use mechanism when we want to get some web pages just by clicking on hyper links.

EX: If we click on "contactUs" and "aboutUs" links in webpages then we are able to get contactUs web page and aboutUs web page.

Example:

Example79
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="home"/>
12</body>
13</html>
14

ParameterizableViewController — home.jsp

Example80
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@page isELIgnored="false" %>
5<!DOCTYPE html>
6<html>
7<head>
8<meta charset="ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body>
12<h1 align="center">
13<a href="contactUs">ContactUs</a>
14<a href="aboutUs">AboutUs</a>
15</h1>
16</body>
17</html>
18

ParameterizableViewController — contactUs.jsp

Example81
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color:red" align="center">
12Durga Software Solutions<br>
13202, HMDA, Mitrivanam, Hyd-38<br>
14Website:www.durgasoft.com<br>
15Mobile: 9246212143, 8885252627
16</h2><br><br>
17<h3>
18<a href="home"/>Home Page</a>
19</h3>
20</body>
21</html>
22

ParameterizableViewController — aboutUs.jsp

Example82
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color:red" align="center">
12Durga Software Solutions is an IT Training Center, it has 40 branches through out the world.<br>
13Durga Software Solutions has started in 2007, Oct, 2nd on the occasion of Gandhi Jayanthi.<br>
14Durga Software Solutions has started Development Center at Madhapur to provide Software Services.
15</h2><br><br><br>
16<h3>
17<a href="home"/>Home Page</a>
18</h3>
19</body>
20</html>
21

ParameterizableViewController — HomeController.java

Example83
JCode Cell
1 
2package com.durgasoft.controller;
3 
4 
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7 
8import org.springframework.web.servlet.ModelAndView;
9import org.springframework.web.servlet.mvc.AbstractController;
10 
11public class HomeController extends AbstractController {
12 
13@Override
14protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
15return new ModelAndView("home");
16}
17}
18

ParameterizableViewController — ds-servlet.xml

Example84
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/home" class="com.durgasoft.controller.HomeController"/>
14<bean name="/contactUs" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
15<property name="viewName" value="contactUs"/>
16</bean>
17<bean name="/aboutUs" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
18<property name="viewName" value="aboutUs"/>
19</bean>
20<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
21<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
22<property name="prefix" value="/WEB-INF/"/>
23<property name="suffix" value=".jsp"/>
24</bean>
25</beans>
26
📝 Key Takeaways
  • Key ideas of Spring - Web MVC Framework explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end