MVC 1
MVC 1
Spring MVC
Spring Model View Controller
Spring MVC is the module which use for developing web application.
In this module we will see different features & advantages when compared with other web
based frameworks.
Spring MVC has overcome the problem which is available with other frameworks. Almost all
the web-based require component has provided by spring people.
1st Difference
Many of existing web MVC frame work that are there it could be struts, it could be JSF or any
other web MVC modules or web MVC frame work that are there in the market.
If you see most of MVC framework that are there they support the view component as JSP or
HTML only.
They never support any view or any other technology will be a view component to rendering a
view as a output to the end user.
So that is one of the serious problems that are there in many of the web MVC framework that
is there in the market.
Why because any of the web MVC frame work that is there in the market will always assumes
the view as a concrete component that is never be change and always default view technology to
be JSP or HTML only .
Unlike existing web MVC frame work likes comes to the Spring, Spring never assumes the
view as an concrete component.
Spring always assume that view as an Interface type.
That does not mean that Interface is the view .That means it always has to design to have a
swapping and placing anything as a view.
Spring never model as the view as a concrete component rather it has always has been design
keeping in view as Interface because in spring you can assume or imagine view as a interface for
which any number of implementation can be render.
In comes to the spring MVC module a view can be not only the JSP or else HTML a view
can be retrieving any other technology it could be PDF,XML,Flex,Flax or a simple image also
which can be capable of rendering the output to the user can be use as a view.
So it is not a concrete component rather view always treated as a interface .So that spring
MVC has flexibility of supporting multiple technology consider as a view .
2nd Difference
In other web-based framework they made request wrapping process automated, but they fail in
handling
Attribute value/conversation.
Ex: If one of the fields is taking int values but user has entered wrong input while mapping it will
generate a big stack trace to the user, which user cannot understand?
In spring if any attribute conversion problem is there then spring will not generate a big stacks
trace rather it will render same page to user along with validation message to render correct data
even it will reserve previous data also.
3rd Difference
In struts to perform request wrapping programmer has to provide one VO class which contain
all the attributes as String & attribute names & input field name should be same.
Moreover programmer has to write struct-config.xml to tell to ActionServlet and that VO class
extends from ActionForm class.
Spring has one command class which help in spring user input in original form there is no need
to type conversion spring has one great feature ie. properrtyEditer which automatically build
corresponding values to particular attributes .
4th Difference
In struts validation logic written by programmer but it become boiler plate logic if there are
multiple view available with same fields then for every view we have to write validation logic
.Validation logic tight to each & every ActionFrom.
We cannot use same validation logic for multiple view/ActionForms.
Unlike to struts, Spring has provided validators which are separate from any of the form. we
can easily use those validators to validate forms.
5th Difference
In struts ActionForm contains total String attributes again programmer has to write VO class
to receive all the actionFrom values to Vo class after that business form to perform that
operations.
Spring has provided command class there is no need to write any conversation logic rather
command is the simple POJO class with original values we can directly use this class to perform
business operations.
6th Difference
To apply common prepossessing logic or post processing logic functionality struts has provided
filter as web component.
Unlike struts, Spring has provide more advanced feature i.e. interceptors which apply common
functionality.
These Interceptor will not check in entry level these Interceptor are sit in spring MVC level and
called along with controller class those are not called with servlet.
So which controller you want to apply common prepossessing logic or post processing logic
you can apply.
So if url also change there is no effect of Interceptor.
7th Difference
Many of the frameworks like Struts doesn’t has support for themes resolver, Time zone Locales
and so on.
Spring has provided a greater support for them resolver Time zone & so on .It also support
internalization.
8th Difference
In struts writing strut-config.xml is critical job because programmer has to write mapping
configuration i.e. Form mapping as well as action mapping.
If there is change in front URL then again we have to change struts-config.xml, maintenance
cost more.
Unlike struts, Spring doesn’t provided an configuration file, it’s automatic process in spring if
there is change so there is no need change anything.
9th Difference
In struts ActionClass read the data to the JSP inform of ActionForm .
In Action class execute() method will be called as a parameter request, response, ActionForm,
ActionMapping as a return type as a ActionForward .
I can read the data from JSP page in terms of ActionForm .but we never use req.getparameter()
then why I write the req.
The request, responses are not required but we are writing un-necessary.
But when it comes to spring we can model our controller in such a flexible way , what is been
required as an input we can take only those parameter in the pojo classes that is added in spring
3.2.
When user send the request it will be received by DispatcherServlet. Now DispatcherServlet
asks the HandlerMapping to give the Controller information to whome he has to send the request
by giving incoming url.
Now HandlerMapping will take the url and map the appropriate Controller and return the
Controller information to DispatcherServlet.
Now DispatcherServlet will forward the request to Controller for processing the request. Now
controller will process the request and return back the logical view name to the DispatcherServlet.
After getting the logical view name DispatcherServlet will ask the ViewResolver to resolve the
view by passing logical view name.
View resolver will take the logical view and creates the object of the view which should be
rendered by DispatcherServlet and return the View Object to DispatcherServlet.
Now by getting the View Object DispatcherServlet will render the appropriate view.
In this way Spring MVC flow works. In the above explanation we have understood the overall
flow of spring MVC.
Let’s see how each and every component declared above in spring mvc perform their task to full
fill the users request through small web application-
In above project directory structure FirstMvcWeb is the root directory of our application.
This application will show how to render the home.jsp.
In a typical web application we put jsp pages in WebContent directory but in above application
we have to put the home.jsp inside the WEB-INF.
In case of Spring MVC it is recommended to keep View inside the WEB-INF.
Let’s see what happens when we keep view in WebContent directory in case of Servlet and Jsp or
Struts framework-
1st Problem
WebContent is a public directory.
Views in this directory can be accessed by any users directly.
In this case our presentation layer technology will get exposed to End-User.
2nd Problem
As End-User can directly access the view he or she may send the request to access the view
which expect some data as input.
In this case user will get an ugly error message which will give bad experience of using our
application to the user.
3rd Problem
If users of our application is technically strong then they might hack our application by using
session and knowing the type of view (jsp/html).
Ex: Let’s suppose our application is for booking movie ticket a user comes and book ticket and
live the system without logout to the page another user comes and he request the same view page
with same url and in same session then he will also gets the same ticket with same information as
that is booked by first user. It will be the biggest problem.
4th Problem
Whenever every time change the URL Google search engine will not able to recognize the
URL.
Advantages in place the views inside WEB-INF
In case of Servlet and JSP or Struts or any other framework except spring MVC views are
either JSP or Html.
There is no point in placing the views in WEB-INF to abstract it from user.
That’s why it is not recommended to place the views inside WEB-INF.
In case of Spring MVC views may be anything like jsp, html, xml, pdf, Excel Sheet etc.
So, due to above reasons it is recommended to place the views inside WEB-INF directory only.
WEB-INF is the protected directory in the project directory structure.
Anything placed inside the WEB-INF directory can be used by application component only.
It cannot be used by user directly from outside.
In this way our views will be abstracted from end user and our application does not suffer the
Internals
Now Let’s first create the home.jsp page and put it in the WEB-INF directory-
Now we want to access home.jsp to access it we cannot send the request directly to the
home.jsp because it is inside the WEB-INF directory.
It can be accessed by application internal component only which is Controller.
Controller will access home.jsp but the problem is we cannot send request directly to the
controller because it is not JEE component.
To send the request to the Controller DispatcherServlet comes into picture.
DispatcherServlet is the component which is provided by spring.
It is the single entry point to our application.
It is the front controller in our application which will forward the request to controller to
handle the request.
Now to forward the request to Controller we need DispatcherServlet so, let’s configure the
DispatcherServlet in descriptor file (web.xml) as follows-
But, DispatcherServlet does not know to which controller it has to forward the request. To
solve this problem of HandlerMapping comes into picture.
It will take the incoming request from DispatcherServlet and finds the proper Controller for
that request.
We can write our own HandllerMapping class and configure it as a bean, but the problem is
DispatcherServlet will not know which method of our class has to be called.
So, when we write our own HandlerMapping class then we have to implement it from
HandllerMapping Interface and override the getHandler(HttpServletResquest request) method
provided by Spring like following-
Instead of writing our Own HandlerMapping spring has provided lot of implementation class
for HandlerMapping which we can use to map the Controller. Some of the HandlerMapping
implementation in which of them is SimpleUrlHandlerMapping.
But it cannot create because,it will get tightly coupled with it. To solve this problem spring has
provided dependency injection mechanism.
DispatcherServlet will create IOC container by reading the spring bean configuration file.
Spring bean configuration file name should starts with <servlet-name> configured in web.xml
then append ‘-servlet.xml’ to it.
Let’s configure SimpleUrlHandlerMapping in spring bean configuration file-
dispatcher-servlet.xml
In the above configuration file viewHomeController will be the bean id of View Controller
which we will configure in dispatcher-servlet.xml later.
Now DispatcherServlet will get the SimpleUrlHandllerMapping bean from IOC container and
keep it as HandllerMapping reference because it will not know which HandllerMapping is
configured by programmer.
SimpleUrlHandlerMapping will take the request and try to match the incoming url to the
configured property key of mappings url if matched then it will return the value which is the bean
id of the Controller to DispatcherServlet.
Now by getting the bean id of the Controller DispatcherServlet will get the Controller from the
IOC container and forward the request to it by calling handleRequest(request,respose) method.
Now Let’s create a Controller class which will handle the request and then configure it
in spring bean configuration file (dispatcher-servlet.xml).
Just creating any class will not become Controller class because DispatcherServlet will not
know which method it has to call to forward the request.
So spring has given an interface called Controller and its multiple implementation class.
To make our class as Controller class we have to either implements from Controller interface
Now After getting the ModelAndView object from Controller DispatcherServlet has to render
the view but it does not know which type of view he has to render.To solve this problem
ViewResolver comes into picture.
ViewResolver is the component which will take the logical view name and resolve it to the
View class object which is to be rendered.
Now DispatcherServlet has logical view name so it will call the ViewResolver by passing the
logicla view name.
To get the ViewResolver Dispatcher Servlet will have to find it in IOC container.
Again there are lots of ViewResolver impementations are provided by spring so we not need to
create our own ViewResolver.
Let’s use one of the ViewResolver implementations provided by Spring. Here we are using
InternalResourceViewResolver. dispatcher-servlet.xml
Now ViewResolver will takes the logical view name and appends prefix and suffix to it to get
the view location after finding the view it will creates the View Type(Jstl for jsp) class and its
object which is to be rendered and returns the object of that class to DispatcherServlet.
Now DispatcherServlet will call the render(model) method of that View class by passing model
(data) to render the respective view to the user.
In this case there is no data so model will be null and home.jsp page will be rendered.
In this way various components of Spring MVC communicate with each other to process the
request.
We should create an extra directory for all the view under WEB_INF...
The outside people who are not part of the application those are not able to access the content
of WEB-INF
Because WEB-INF are the protected DIRECTORY in the Web-Application..
The only who are internal part they are only able to access so controller able to access The
WEB-INF
The controller will tell to the dispatcher servlet which view have to render...after complete the
processing the request controller tell the dispatcher to render the view...
Its recommended to give the Servlet name as dispatcher servlet. The class name of the servlet is
org.springframework.web.servlet.DispatcherServlet
The Dispatcher servlet don’t know how to processing the request...programmer know how to
processing the request.
The dispatcher servlet create the IOC container For one time with in the lifetime of the
application so its create in init().
The name of the servlet we give in the web.xml its look in the application config file as
‘dispatcher-servlet.xml’ and its create the IOC and we have to create it in WEB_INF
Whenever request came into DispactherServlet its don’t know how to process it....so the
programmer know how to process it
So we are configuration the handler mapping in Spring Bean configuration file
With in a typical Web application there are some other part rather than the presentation
layer....so we want HandlerMapping, Controller also required.
As well as the Business tier component and persistence logic also required... Like Service and
dao......
Controller is going to call the service. dispatcher servlet will call the Controller.
Service has to inject to controller and dao has to inject into the service and we have to
configure in spring bean config file.
I have more than one controller. I have bunch of controller are there with in mvc application. if
all are have to config into dispacther-servlet.xml.
But the problem is there if we don’t want tomorrow, the spring Framework in presentation
layer then there is a problem to extract the business component and persistence component.
If dispatcher has to create the IOC with including the Service and dao then we can’t not
separate them.
So we need an extra component who is able to create the IOC container for the Business and
persistence tier of application
So I have to write and different spring bean config file and create an extra IOC so tomorrow if
we change our framework to struts then no need to writes DAO and Service again
The service has to inject into the Controller so service and dao are created before controller
has created.
So find someone who able to read mah spring config file and create and IOC container during
the start-up of application that is ContextListner
its take service and dao and create an ioc container ....
So i have to create an contextListner ......every application has needed of listener so spring has
provide a listner class ContextLoaderListener.....
It creates an ioc container just the application start-up time before servlet has been Instantiated
by servlet-config..
So we have to pass the config file the contextLoaderListener...when we pass the servlet values
as init-param so to listener we pass context-param
Example#1
Internal of Request processing in spring MVC?
Once the request comes to DispatcherServlet then it will passes to controller for processing
further processing by help of HandlerMappling.
But to receive each and every request first we have to configure DispatcherServlet into web.xml
with standard url pattern.
For a servlet-name we can use any name but it is recommended to use dispatcher and the
servlet-class should be fully qualified name.
Once DispatcherServlet has been configured in web.xml now we have to look for other
component which help Dispatcher to fulfil the request processing.
Now other components are HandlerMapping ,ViewResolver, controller these component
written by programmer because programmer is the who know for which url pattern which
controller has to map and once controller return the logical view name to the DispatcherServlet
which view has to be rendered.
These things know to the programmer but we have to tell to the DispatcherServlet these are the
component which help you to fulfil the request processing so to tell to the Dispatcher we have to
write one spring bean configuration file which contains all the additional components as bean.
But how DispatcherServlet going to read this spring bean configuration file ,for that we have to
follow some standard to writing that bean file .
Spring bean file name should be “dispatcher-servlet.xml”(<servlet-name>-servlet.xml).Then
only DispatcherServlet will able to read that file.
While servlet loading in init method it will read the dispatcher-servlet.xml file and place as a
IOC container in logical memory, means load-on-startup all the beans going to be created and
place into logical memory of the IOC container.
Now my DispatcherServlet can easily talk to the other component to accomplish the request
processing because all are the part of same IOC container.
Rather than controller ,viewResolver other component also will be there for example service,
DAO and so on ,there are 100’s controller services and DAO’s will be there then it is very hard to
place all into one spring bean configuration file.
Some of them presentation specific beans and some of them Business and persistency also so it
is very difficult to identify each other, and if there is change in one of the beans we have to check
entire file ,means readability is not there and more over my presentation logic mix with business
logic and persistency logic.
If i want to change presentation tier then all my business and persistency gets collapsed because
of all are part of one spring bean configuration file.
To keep my Business and Persistency tier safe at any situation we not mix with presentation
tier.
Write one more configuration file and it contains Business tier and Persistency tier bean only
.But writing configuration file is not enough we have to tell to the DispatcherServlet /some one to
read this file into IOC container .
Now check the dependency if any service and DAO’s are there then only controller going to
speak to service and service is speak to DAO’s.
If service is there then we can inject service into controller if DAO’s are then we can inject
DAO’s into service.
Means before loading my DispatcherServlet my other bean file has to be loaded then only we
can inject service to the controller and DAO’s to the service.
So what is the name of the new bean file i.e. application-context.xml.
So which is the component who get’s loaded at first moment once the servletContext object has
been created i-e. contextListeners.
Listeners are the classes which get’s loaded more early then any of the other component so to
load application-context.xml spring has provided one Listener called ContextLoaderListener .
So we have to configure this listener into web.xml file with application-context.xml file to tell
to the ContextLoaderListener.
Then we have to configure context parameter which going to point our application-context.xml
and ContextLoaderListener can easily read that file and create logical memory by placing IOC
container which contains all beans.
Now First my application-context.xml going to load by Listener after that my
DispatcherServlet going to create another IOC container by loading dispatcher-servlet.xml.
Now both the IOC container are the part of one project if they wanted to talk to each other
then spring has to used nested IOC container concept.
ContextLoaderListener is the web component and it is the first component of servlet container
which gets called by servletContainer .
Actually ContextLoaderListener is the spring specific listener but it has been extend from
ContextListener which is servlet container part .
What is the reason to create two IOC container and how they going to
inject with each other.
First of all spring is the non-invasiveness
non invasiveness framework to keep that promise spring allows
programmer to create two IOC containers.
dispatcher-servlet.xml one for spring specific component.
applicationContext.xml one is for Business layer component means in future if we don’t want
to use spring mvc then we can get read out from spring mvc easily without disturbing the existing
business tire logic and we can replace any web-based
web based frameworks to work with rest of the
component easily.
How internally both IOC container gets created and interact with each
other ?
First ContextLoaderListener will create an IOC container by reading application-context.xml
application
which we have given input by configuration into web.xml.
It will read spring bean configuration file and it will create IOC container by placing all beans
into IOC container.
Once it created IOC container, It will place the reference of that IOC container into Servlet
context when my DispatcherServlet start to create IOC container before that it will check any
parent IOC reference available into servlet context
context or not if it is available.
Thin it will take an reference and pass to the DispatcherServlet created IOC container to create
IOC container along with parent ent reference(nested
reference bean factory concept ) means both can easily
can interact with each other.
like this not exactly…
ApplicationContext parent=new new ClassPathXmlApplicationContext("applicatioContext.xml"
"applicatioContext.xml");
ApplicationContext child=new new WebApplicationContext("dispatcher-servlet.xml"
servlet.xml",parent);
Spring application has two types of context configuration files for Spring MVC module:
1. ApplicationContext (default name for this file is applicationContext.xml)
2. WebApplicationContext (default name for this file is xxx-servlet.xml
servlet.xml where xxx is the
DispatcherServlet name in web.xml)
ApplicationContext
applicationContext.xml one is for Business layer component means in future if we don’t want
to use spring mvc then we can get read out from spring mvc easily without disturbing the existing
business tire logic and we can replace any web-based frameworks to work with rest of the
component easily.
Spring loads applicationContext.xml file and creates the ApplicationContext for the whole
application.
There will be only one application context per web application.
If you are not explicitly declaring the context configuration file name in web.xml using the
contextConfigLocation param,
Spring will search for the applicationContext.xml under WEB-INF folder and throw Exception
if it could not find this file.
We can add multiple configuration.
WebApplicationContext
Apart from ApplicationContext, there can be multiple WebApplicationContext in a single web
application.
In simple words, each DispatcherServlet associated with single WebApplicationContext.
xxx-servlet.xml file is specific to the DispatcherServlet.
Spring will by default load file named “xxx-servlet.xml” from your webapps WEB-INF folder where
xxx is the servlet name in web.xml.
If you want to change the name of that file name or change the location, add initi-param with
namespace as param name and value is filename .
If you are not explicitly declaring the context configuration file name in web.xml using the
contextConfigLocation param,
ContextLoaderListener
Performs the actual initialization work for the root application context.
Reads a “contextConfigLocation” context-param and passes its value to the context instance,
parsing it into potentially multiple file paths which can be separated by any number of commas
and spaces, e.g.
“WEB-INF/applicationContext1.xml;WEB-INF/applicationContext2.xml”.
ContextLoaderListener is optional. Just to make a point here: you can boot up a Spring
application without ever configuring ContextLoaderListener, just a basic minimum web.xml with
DispatcherServlet.
We can write one our own class by implementing from controller and we can override that
method for handling the request.
One more abstract class has to provided by spring to works with controller, we can use that
abstract class to create an controller and i.e.
AbstractController(Abstract class)
ModelAndView handleRequestInternal(req,resp)
Let’s see if we extending our class from AbstractController what is the flow in diagrammatic
representation.
How dispatcher servlet know which HandlerMapping its has to go?
Its directly go to the IOC because it’s have the ref of WebApplctionContext as attribute ..
Spring people has provide an interface all the handlerMappping are implementation from its so its
always look for an Interface not the implementation class.
Whatever you have wrote its search for Interface so we have to flexible of our own HanlerMapping
also we able to create. it is called polymorphism.
HandlerMapping mapping=webApplicationContext.getBean(SimpleUrlHandlerMapping.class);
Example#2
Controller Class
web.xml
application-context.xml
webmvc-servlet.xml
HandlerMappling
Whenever DispathcerServlet has received the request, He has to map the request to controller.
But dispatcher servlet will not know for the given request which controller class the programmer has
to write in HandlerMapping ,for which request which is the controller to the DispatcherServlet.
So the DispatcherServlet is the one who is receiving the request but as it don’t know which controller it
need to call that’s why the dispatcher servlet will talk to the HandlerMapping .
How does the HanderMapping will know for which request what is the controller
that has to delegate the request to ?
That is something that has to be configure by the programmer For the information related to the request
and the controller to this the request has to be mapped to the hendlerMapping .
So that upon receiving the request the DispatcherServlet Quickly approach to the HandlerMapping in
identifying the controller based on the configuration we have given .
So that the HandlerMapping give the name of the controller to the DispatcherServlet .
How do I need to work with HandlerMapping ?How can i use the HandlerMapping
?
You can write your own HandlerMapping but you can’t write any class and you can’t call as a
HandlerMapping class.
If you are writing your own HandlerMapping then your class must should have implement
HandlerMapping Interface and should override one method i.e.HandlerExecutionChain
getHandler(HttpServletRequest request) which is going to take the request and going to returns the
HandlerExecutionChain.
But it not required to defined our own HandlerMapping ,because Spring itself has provided lot of
implementation classes for the HandlerMapping interface.
So you never need to find a requirement with creating your own HandlerMapping by implementing
HandlerMapping interface Such a use case will not come .
Because Bunch of HanderMapping implementation class has provided by the spring as part of the
Spring MVC.
You can use one of the HandlerMapping rather than creating your own handlerMapping.
SimpleUrl HandlerMapping
SimpleUrlHandlerMapping is called as the most easiest and flexible url handler mapping in the spring
mvc.
The name itself will tells that it is a url handler mapping bean where the incoming url is directly taken
as an input and base on the url it is going to map the request.
So give me the url based on the url SimpleUrlHandlerMapping can quickly find out the handler
component .
This Handler mapping will takes url as an input by considering the url they map the request to the
controller .I.e Programmer has to tell which url explicitly what is the controller that has to map the request
based on the url.
It is the responsible to the programmer for which request what is the corresponding controller
This is useful to map the incoming request with controller class based on valid paths of request url and
bean ids/names of the controller class.
We need to supply the details of values of “mappings” property of type (java.util.Properties)
Ex:
If the request url is contains “/home.htm” then it passes the request to ViewHomeController class
whose bean id/name as “ViewHomeController”
Here any controller can map with any url .your classes are not tight with url the id of the class is being
map with url .if you want to change it you can independently change the controller .
The benefit to going with SimpleUrlHandlerMapping is what it even permit to have wild card
character also as part the uri(hm*.htm)
You can map multiple url also in one controller .
Here programmer gets flexibility to map controller and he can map multiple url to to one controller
also.
BeanNameUrlHandlerMapping:
BeanNameUrlHandlerMapping is the default handler mapping .
If you don’t provided any HandlerMapping then spring by default expose
BeanNameUrlHandlerMapping.
It is like SimpleUrlHandlerMapping only the different is here programmer going to configure
beanName as url pattern which is match to incoming request url.
It is looks like
It will match incoming request url and corresponding bean name if any of HandlerMapping going to
match .It will call corresponding controller .
ControllerClassNameHandlerMapping
This controller falls under conversion over configuration.
There is no need to configuring additional beans or url mapping into config file.
The name itself tells you by using controller class name the HandlerMapping going to happen.
Ex:
The ControllerClassNameHandlerMapping will take class name as url by removing ‘Controller’ word
from the class because it is common to each and every controller class.
Addition to that we have to configure some additional properties also.
if it is required we have to configure a property caseSensitive=true/false
ControllerBeanNameHandlerMapping
The corresponding controller going to indentified by the BeanName i.e id.
But incoming url is different and configure id is different.
How it will going to match.For this we have to configure additional property in
ControllerBeanNameHandlerMapping i.e
Suffix=.htm /.action/.mvc/ .view
It will works with both the configuration i.e *.htm /*
When you use *.htm then just configure that class with additional property name that class with
additional property name ‘suffix’ and value is .htm
1. ParameterizableViewController(C)
2. UrlFileNameViewController(C)
3. AbstractController
4. AbstractCommandController
5. MultiActionController
6. SimpleFormController
7. AbstractWizadController
Abstract Controller
What is the Benefits when we use Abstract Controller and why we should not use
controller interface?
Actually, before processing any request and controller has to check is it GET method or POST method.
It is valid method or not, after that he verify other data and so on then only it will call our class
overridden method to further processing.
If we write validation method checking and other verification in controller then we end up with
duplication in controller then we end up with duplicating same logic across each and every controller
because of that AbstractController implements controller and the provided implementation for
handlerRequest() method.
In handlerRequest of Abstract class contains verification logic after verification handlerRequest method
will call our class handlerRequestInternal for further processes.
We use AbstractController used when we wanted to rendered dynamic data.
There are some characteristics for when to use AbstractController
1. No Request data
2. No Request Wrapping
3. No form Handling
But just clicking on link it has to perform the further processing.
Example#1
Upon clicking a hyperlink/link we wanted to display a dynamic data then we can easily use above
controller.
When we should go for AbstractCommandController
This controller can be used at many places, it is specific to searching, as part of request, request data
is there and request wrapping also there but FormHandling is not there then we can use this
Controller.
Here command represent a form and form represent input controller/data ,In spring command is a class
which able to hold incoming data from the user.
All command attributes must same as input controller name.
add-journey.jsp
Example#2(Show Dynamic page and edit option)
Importance of formBackingObject()
Generally when handleRequest() method is processing initial phase request it internally calls
formBackingObjec() to create command class Object .
The Pre defined method always creates the empty command object .
If you want to create command object with dynamic data according to application requirement then we
need to override this method in our controller class that extends form SimpleFormContorller.
Verifing the format and pattern of form data is called form validation.
Spring MVC allows to write form validation logic in separate class so that it can be linked to multiple
controller classes having reusability.
To write a validator class we have to implementing our class from validator interface and override
support(--) and validate(--) methods.
Write properties file having validation error messages.
Write ResourceBundleMessageSource and give the base name so that it can read that file from class
path.
Configure validator class in dispatcher-servlet.xml and link that class with controller class using the
property ‘validator’.
Place the <form:errors path=”*”> tag in jsp form submission page to display the form validation error
messages.
The Simple controller can handle Three types of validations
1. Form Validation(like number/name can’t be blank)
2. typeMismatch error (like date dd/mm/yyyy)
3. Application Logic errors like (not allowed so and so value to particular type)
Instead of hard coding error message directly in validator class and controller class it is recommended to
place in properties file having our choice key and values.
But typeMismatch errors the key should be typeMismatch(properties ) you have to take.
What is the Use of support(Class class) method and validator class of Validator
class?
The support method holds the configured command class parameters and we can check whether the
correct command class is configured or not using the Class class type calling AssignableForm(class)
method.
If configure correctly it returns true otherwise it returns false ,so validate method will not execute.
Due to this we can avoid mis configuration in spring bean configuration file.
BindingResult(I)
When dispatcherServlet pass request as input to the simpleFormcontroller extract the data and perform
the request wrapping and internal process, while conversation if there are some type conversion errors
then it will not throw an ugly exception in the user.
Controller internally Bind that Exception Result to the Binding Result object like that if any internal
Exception are there it will preserves .
After that it will call validator class to validate other attributes of command class by creating errors
object.
If at all any errors are there we will bind them to errors object.
Once validation finished, controller checks errors.hasErrors() method if errors are there then it will bind
that errors to commandName.errors and command object and return to DispatcherServlet.
DispatcherServlet call viewResolver to display the view form tag will conversation it will check first
errors are there or not if at all there it will show those errors by presenting old values into test boxes.
The old values preserved by command object if at all any type conversion errors are there then such
kind of values preserves by BindingResult Object.
ViewResolver
Spring has supplied few predefined view Resolver classes. They are :
InternalResourceViewResolver(sub class of UrlBasedViewReslover)
ResourceBundleViewResolver(configure view in property file)
XmlViewResolver(configure view in xml file)
BeanNameViewResolver(resolver spring beans as views)
UrlBasedViewReslover
InternalResourceViewResolver:
Useful to resolve jsp, of WEB-INF folder as views by default takes “JstlView” as view class.
Reporting in PDF (iText Lib) and EXCEL (Poi Lib)
What Handler Interceptor why not Filter?
I have some common pre-processing and common post processing that i want to apply for each and
every request that is coming to my application .
In case of servlet and jsp we need to write that in Filter .
In servlet and JSP filter is always applicable but in spring mvc always the request is received by
DispatcherServlet .
Client will send the request to the DispatcherServlet , DispatcherServlet will forward the request to
HandlerMapping , HandlerMapping will identify the controller and return the id of the controller to
DispatcherServlet.
Then DispatcherServlet will forward the request to the controller .
Whenever the request is coming to DispatcherServlet ,the servlet container will indentifies for this target
which is a Filter that has to get executed then the Filter doFilter() will be called.Then the Filter will
complete pre-processing then forward the request to Dispatcher Servlet.
Dispatcher Servlet will handle the request. then forword the response to Filter then Filter will perform
post processing the send the response to the client .
Whenever i send the request DipatcherServlet will received the request
Whenever DispatcherServlet received the request Then Dispatcherservlet will not check whether the
request is valid or not It directly send the URL to Handler Mapping.
So that un-necessarily for a valid request or invalid request always the filter is executed.
So Filter is not a relevant solution when it comes to spring MVC .
So Handler Interceptor Came into picture.
Handler interceptor
We have one more additional component to HandlerMapping is a Interceptor .
So that whenever the DispatcherServlet received the request it forward the request to Handler Mapping
, send the URl , Handler Mapping is trying to find is the URL is a relevant controller.
If the controller is identified, the name of the controller along with that the Interceptor that should
execute for this controller both should be pass as the input for the DispatcherServlet.
Now Dispatcher Servlet create Handler Execution chain because we can add any number of
Interceptor like security interceptor, Http Monitoring interceptor and logging interceptor .So multiple
interceptor can apply for a request. So all the interceptor add to handler mapping .
Handler Mapping will identify the controller and the list of Interceptor that has to be executed in the
order before the request will goes to the controller it create a handlerExicutionChain .
Example
dispatcher-servlet.xml
maintainance.jsp
Annotation
Important Possible input parameter to a controller
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpWebRequest
5. HttpWebResponse
6. Command class
7. Model
8. ModelMap
9. Form Class @ModelAttribute
10. BindingResult
11. BindingException etc…
Example#1
Example#2
Example#3
Example#4
Example#5
Example#6
search-medicine.jsp
medicine-info.jsp
End to End Application including Log4J (Configuration and Annotation
Mixed)
add-product.jsp
add-product-success.jsp
ServletConfig
application-context.xml
persistence-beans.xml
Spring ORM
Spring ORM framework allows you to integrate with hibernate , Java persistence API(JPA) ,Java Data
Object (JDO) and iBATIS for resource management and data access object (DAO) implementations and
other startegies.
Easier Testing :Spring IOC approach allows you to swap easily the implementations and configuration
location of HibernateSessionFactory instances . so that you can point your configuration to various
environment without modifying the source code.
Common data access Exception: Spring instead of exposing ORM specific checked exception to the top
level tier’s of the application, It will wrap the technology specific exception in to a common runtime
DataAccessException Hirarchy.
Integrated Transaction Management: Instead of dealing with ORM technology related transactional
related code ,It allows You to declaratively manage the transactionality using AOP Declarative
Transaction management tags <tx:advice or Annotation driven @Transactional annotation
In order to use Spring ORM with hibernate ,You need to declare your Hibernate Language Object using
declarative mapping.hbm file or annotate your classes with hibernation annotations , In order to perform
the Operations using these classes You need to declare the Hibernate SessionFactory and then inject into
Hibernate Template it allows us to perform the Database operations using Template Approach.
To create Hibernate Template object we need Hibernate Session Factory object.
Then the Hibernate Template will injected to DAO to perform the persistency operation.
ORM Configuration Annotation and Configuration(Annotation Class)
ORM Configuration Annotation and Configuration (MappingResource)
ORM Configuration Approach
Spring With Hibernate Integration Annotation Approach Example
InitFormBinder
While working with form binder we can override initBinder(--,--) method to register properties editor
that are required to use while binding given form data.
If we are using annotation approach we can add validator through @InitBinder and initBinder(--)
method.
Spring Security
To perform dependency injection on servlet filter component it can’t be possible because its class must
be maintained by IOC container as spring bean having configuration in spring bean configuration file.
Due to this it can’t take request from client as filter is not configured as web component in web.xml file.
To overcome this problem we configure a special proxy filter in web.xml file to take the request from
the client to pass the request to filter component that is there in IOC container as spring bean.
The special filter is “org.springframework.web.filter.DelegatingProxyFilter”.
But we need to match logical name of DelegatingProxyFilter with bean name of filter component.
If the resource the user is requesting has to be authorise user can access then it goes to the session check
current user is logged in or not by check to the session If not redirect the user to the login.jsp page and
asking to logged in before accessing the resource .
If the user is already logged in the resource authority and user authority is matching or not .
If matching forward the request to the resource if not throws an Exception saying unauthorised access of
the resources. All these thing doing by the Authentication Filter .
Security is something is required all the application that’s why the underline J2EE is provided the
Security mechanism .
If you use j2ee Security all the component we are not to write J2ee provide some commonest like
Authentication Filter,login and LoginServlet ,Autentication Manager ,Authentication Provider and
Authentication Store .
Why Authenticate Provider will not validate the username and password ?
Validation logic must be rewritten in other class when we switch from one Authentication Store to other
Authentication Store.
Validating the credential are be separate from fetching the credential from Authentication Store .
Authentication provider will access the details and passes the input to the Authentication Manager.
Authentication Provider will fetch the username related record from the authentication store with which
we need to compare the provider username and password is matching with the Authenticate username
password .
That mean the Authenticate provider we need to pass the login username .Then he is going to pass
User Details Object .User Details Object means Username, password, Role of the user will pass the input
to Authentication Manager.
We can configure spring security definitions in spring bean configuration file having security name
space , based on the configuration internally one ServletFilter will be generated as spring bean in IOC
Container having bean name as “springSecurityFilterChain” so to take request from client add to pass to
request the above generated filter we need to configure “DelegatingFilterProxy” in web.xml with logical
name “spring SecurityFilterChain” .
1. spring-security-config-3.0.5 RELEASE.jar
2. spring-security-core-3.0.5 RELEASE.jar
3. spring-security-web-3.0.5 RELESE.jar
To use Web security we need
Authentication Store Spring has provided its own Authentication Store if You
want to store data in other Authentication Store you need to
write your own Authentication Provider by implementing
your class from userDetailsService
Authentication Provider Spring has provider
Authentication Manager Spring has Provided
Login Servlet Spring has provided if you want your own login page you can
write but you need to security-beans.xml
Filter Spring has provide DelegatingFilterProxy we need to
configure as “ spring SecurityFilterChain”
Role Configuration You need to configure that in spring bean configuration file.
No need to write in web.xml
Basic Authentication
dispatcher-servlet.xml
security-beans.xml
web.xml
Database Authentication