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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

app1 — WishController.java

Example28
Loading editor…

app1 — ds-servlet.xml

Example29
Loading editor…

app1 — web.xml

Example30
Loading editor…

app1 — index.jsp

Application-2

Example31
Loading editor…

app1 — hello.jsp

Example32
Loading editor…

app1 — welcome.jsp

Example33
Loading editor…

app1 — HelloController.java

Example34
Loading editor…

app1 — WelcomeController.java

Example35
Loading editor…

app1 — ds-servlet.xml

Example36
Loading editor…

app1 — web.xml

Example37
Loading editor…

app1 — index.jsp

Application-3

Example38
Loading editor…

app1 — helloform.html

Example39
Loading editor…

app1 — wish.jsp

Example40
Loading editor…

app1 — HelloPageController.java

Example41
Loading editor…

app1 — WishController.java

Example42
Loading editor…

app1 — ds-servlet.xml

Example43
Loading editor…

app1 — web.xml

Example44
Loading editor…

Application-4 — index.jsp

Example45
Loading editor…

Application-4 — loginform.jsp

Example46
Loading editor…

Application-4 — Success.jsp

Example47
Loading editor…

Application-4 — failure.jsp

Example48
Loading editor…

Application-4 — LoginPageController.java

Example49
Loading editor…

Application-4 — LoginController.java

Example50
Loading editor…

Application-4 — ds-servlet.xml

Example51
Loading editor…

Application-4 — web.xml

Example52
Loading editor…

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
Loading editor…

Example-5 — index.jsp

Example58
Loading editor…

Example-5 — loginform.jsp

Example59
Loading editor…

Example-5 — status.jsp

Example60
Loading editor…

Example-5 — LoginController.java

Example61
Loading editor…

Example-5 — ds-servlet.java

Example62
Loading editor…

Example-5 — web.xml

Example63
Loading editor…

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
Loading editor…

Spring Web MVC Application with MAVEN — helloform.jsp

Example66
Loading editor…

Spring Web MVC Application with MAVEN — wish.jsp

Example67
Loading editor…

Spring Web MVC Application with MAVEN — HelloController.java

Example68
Loading editor…

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

Example69
Loading editor…

Spring Web MVC Application with MAVEN — web.xml

Example70
Loading editor…

Spring Web MVC Application with MAVEN — pom.xml

Example71
Loading editor…

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
Loading editor…

AbstractController — wish.jsp

Example74
Loading editor…

AbstractController — WishController.java

Example75
Loading editor…

AbstractController — ds-servlet.xml

Example76
Loading editor…

AbstractController — web.xml

Example77
Loading editor…

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
Loading editor…

ParameterizableViewController — home.jsp

Example80
Loading editor…

ParameterizableViewController — contactUs.jsp

Example81
Loading editor…

ParameterizableViewController — aboutUs.jsp

Example82
Loading editor…

ParameterizableViewController — HomeController.java

Example83
Loading editor…

ParameterizableViewController — ds-servlet.xml

Example84
Loading editor…
📝 Key Takeaways
  • Key ideas of Spring - Web MVC Framework explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.