0% found this document useful (0 votes)
15 views

MVC 1

Spring MVC

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

MVC 1

Spring MVC

Uploaded by

Anil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Spring Material: Part-5

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.

Differences between spring MVC and Other web-based Framework?

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.

Spring MVC Flow

Let’s understand overall how spring MVC works-


In case of Spring MVC user has to send the request with extension *.htm or *.mvc or *.web or
*.action depends on the DispatcherServlet configuration wild card pattern.

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-

Project Directory Structure for Spring MVC

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-

web.xml (Deployment Descriptor File)


Now when user send the request with url /home.htm it will be received by servlet container
and it will go to deployment descriptor file (web.xml) as there url-pattern is *.htm it will match
with that and forward the request to DispatcherServlet.
Now DispatcherServlet will forward the request to Controller.

But, DispatcherServlet does not know to which controller it has to forward the request. To
solve this problem of HandlerMapping comes into picture.

HandlerMapping is a component which will map the incoming request to corresponding


Controller.

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.

In our first application let’s use SimpleUrlHandlerMapping.

As this implementation class is provided by spring DispatcherServlet knows which method it


has to call to get the handler (Controller).

Now to call the getHandler(…) method DispatcherServlet needs object of


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.

Configuration file name should be “<servlet-name>-servlet.xml” by default DispatcherServlet


will looks for the dispatcher-servlet.xml file to create the IOC container.

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.

After that DispatcherServlet will invoke getHandller(HttpServletRequest request) method of


SimpleUrlHandllerMapping to get the Controller bean id.

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.

So, let’s configure the ViewResolver in spring bean configuration file(dispatcher-servlet.xml).

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

We have not configured InternalResourceViewresolver with bean id because


DispatcherSerrvlet treat all Implementations of ViewResolver as ViewResolver only.

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...

Dispatcher servlet is an servlet so we have to configure it under the web.xml....

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.

So he configure an HandlerMapping to identify the appropriate Controller so we have to write


a HandlerMapping in somewhere then dispatcher servlet will go to the HandlerMapping and
takes the request then as per the request its identify an Controller .

So we have to configure in spring-beans configuration file that dispatcher servlet able to


identify the Handle Mapping.

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

its create an IOC where as bean service and dao we configure


If we are not write load-on-startup its will try to create the servlet at the time of 1st request
at the time might be discover some in consistency may occur so we much before to detect them
we have create the Servlet...so avoid the handling the1st req so we have to create it much before...
Even its is optional we its recommended to configure load-on-startup
But we have to create as <load-on-startup>2</load-on-startup>
Because the service has to create by the listener then only it make use of the service and create
another IOC
But application server are create listener first and then servlet
if one component is in one IOC and talk to another IOC container then go for nested IOC
container .
So dao and service is have to parent bean factory and dispatcher have to child bean factory.

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.

What is HandlerMapping? What is the purpose of HandlerMapping


First the user send the request to the Application, Once the application get deployed.
ContextLoaderListener create IOC container after that before executing a particular
DispatcherServlet, init() method gets called.
And Dispactcher-servlet.xml file going to read by that init() method and create another IOC
container.
Once it finish DispatcherServlet takes the request and apply the common processing logic,
system resources and plumbing logic and all once is finish it has to send to one of the controller to
handle the request processing.
But DispatcherServlet don’t no to which controller he has to send that particular request.
So it is known to programmer means programmer has to tell to the DispatcherServlet to which
controller he has to send that request .so to configure number of controller HandlerMapping
comes to picture .

How HandlerMapping is the Component which Keep track the urlpatterns


and corresponding controllers to handle the request ?
The programme has to write one class which going to implements from HandlerMapping and
he can manually write the url and controller into one map to handle it.
But spring has provided some predefined HandlerMapping which programmer has to use one
of them as
|SimpleUrlHandlerMapping ->class
|-mappings
|-props
|-key url
|-values controller
Just we need to configure as bean into dispatcher-servlet.xml and provide corresponding
controller and url information.
Once DispatcherServlet get corresponding controller it will forword/call the controller to
process the request.
But to call that particular controller DispatcherServlet has to know whom he has to call or
which method he has to call .
You cannot write any class and we can’t say this is a controller.
For this we have to write controllers by extending or implementing by spring specific interface
or class.
To write an controller spring has provided one interface and one abstract class which contains
some method, those overridden by our class .
Controller (Interface)
|-ModelAndView handleRequest(req,,resp)

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);

How dispacther servlet come to know its bean id?


getBean has a Method every handlerMapping impl from HandlerMapping Interface By the help of class
we get the Bean ,Handler mapping always talk to the Class its identified by the Class....

Example#2

Controller Class
web.xml

application-context.xml

webmvc-servlet.xml
HandlerMappling

What is HandlerMapping ? What is the purpose of HandlerMapping ?

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.

How Many Implementation Spring has to provided by the HandlerMapping?


Handler Mapping is a component that maps incoming request to controller/handler class.
All Handler Mapping class are implementation of “HandlerMapping interface.
The implementation Handler mapping classes are :
1. BeanNameUrlHandlerMapping
2. SimpleUrlHandlerMapping
3. ControllerClassNameHandlerMapping
4. ControllerBeanNameHandlerMapping (3.0 v)
5. DefaultAnnotationHandlerMapping (2.0v)
6. RequestMappingHandlerMapping(3.2v)
So the spring mvc has provided total 6-HandlerMapping to us so we can use one of this
HandlerMapping to work with our application.
But out of six last two handlerMappings are used in annotation approach only
Initially the spring doesn’t have these many number of HandlerMapping .Initially as part of spring
framework there are only 3 handler Mapping are there.
1. BeanNameUrlHandlerMapping
2. SimpleUrlHandlermapping
3. ControllerClassNameHandlerMapping
As part of spring 3.0 They have added ControllerBeanNameHandlerMapping and 2.0
DefaultAnnotationHandlerMapping is there .
After 3.2 the RequestMappingHandlerMapping has to be added .
So all the HandlerMapping are not there in the Day-1, Those are being added base on the
implementation requirement the people are getting.
So finally we have big 6-number of HandlerMapping that are available.
Out of which DefaultAnnotationHandlerMapping and RequestMappingHandlerMapping we have to
discussed when we have work with Annotations.
If you are using spring mvc with annotation then will the presence the two HandlerMapping will come .
When you have working with configuration approach there 4-you have to work.

Let’s take one Handler Mapping after one Handler Mapping :-

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

Multiple Configuration in DispatcherServlet


How can we register ContextLoaderListener and Dispatcher
Servlet in ServletContext Object without using web.xml ?

Default : Listener class =applicationContext.xml


DispatcherServlet class=dispatcher-servlet.xml
If you want to change default file name
Controllers
As we know controller is not a web component, so controller will not get call directly by container.
First request comes to container and container pass it to DispatcherServlet to serve it,but
DispatcherServlet will not perform request processing completely.
So we need one more component called controller which able to process the request and return the
Logical View Name.
Spring has provided multiple controllers as per our requirement we can use one of them:

1. ParameterizableViewController(C)
2. UrlFileNameViewController(C)
3. AbstractController
4. AbstractCommandController
5. MultiActionController
6. SimpleFormController
7. AbstractWizadController

Q. When we should go for ParameterizableViewController / UrlFilenameView


Controller?
When we want render only static target page (like about-us.jsp /contact-us.jsp )as part of incoming
request then we can use above controller.
These two controller specifically address the static component.

Q. When we should go for AbstractController?


Upon clicking a hyperlink/link we wanted to display a dynamic data then we can easily use above
controller.

Q. When we should go for Abstract Command Controller?


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 .

Q. When we should go for SimpleForm Controller?


If we wanted to perform all the aspect for request processing Like Request contains Data, Request
Wrapping ,Form Handling then we can easily choose the above component/Controller.

Q. When we should go for MultiActionController?


In general if we wanted to handle a request then we have to write one controller for multiple action
multiple controller has to write but spring has provided one controller which allows us to bind multiple
action to single controller. For example page navigation form can have multiple action next, previus...

Q. When we should go for AbstractWizardController:


It is the controller which help the developer to gather the data using multiple wizard.
We cannot gather 100 of records or columns of data using jsp pages .it may load bad user experience to
make good and to gather the data mostly developer follow Wizard conversion and flow driven approach .
ParameterizableViewController
This controller specifically for rendering static component/view.
The name itself tells the upon taking parameters it will return view to perform father processing.
ParameterizableViewController is a concrete class we can directly use and configure inside configure
file. Just it will take one parameter and upon taking it, it will return logical view name for further
processing.
For multiple static components there is no need to write multiple controllers just configure
ParameterizableViewController with multiple id and map inside the HanlderMapping.
But the problem is if 10 static components are there 10 beans id we have to configure.
It is not a good programming rather we can use another controller
//Example SimpleUralHandlermapping
To avoid the above problem one more controller has provided by spring UrlFileNameViewController.

ParameterizableViewController Configuration Ex-1


UrlFilenameViewController
It is also one of the spring controller and it is also a concrete class ,just we need to configure it .
It works open taking an request url and matching that url with filenames and returning a logical view Name
for Father processing.
Just we have to configure one time and we can map that controller to multiple url, So
UrlFileNameViewController will manage it.
Rather configuring multiple ParameterizableViewControllers just use UrlFileNameViewController.
We can easily map multiple url to that bean to handle it.

UrlFilenameViewController Configuration Ex-2

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.

How internally command class read by AbstractCommandController and How it


will call my class by passing command Object ?
Internally DispatcherServlet call my class which extends from ACC and call the handle Request but my
class doesn’t contains any handleRequest.
It will goes to super class and find handleRequest is there or not.
Now ACC has handleRequest method once it found the method, he will read the incoming request i.e.
post means user send some data then it will come to know he has to do request wrapping he will go the
configure file and check any commandclass has been configured or not .if it is there then he will take the
command class and create the object and perform the request wrapping.
Once request wrapping finished he will call my class handle method by passing req,resp,command
object and binding Exception for father processing .
While working with AbstractCommandController we should do the Form Handling because this
controller not ment for form Handling .
DispatcherServlet never perform request wrapping because it is not a command processing logic or
pumbing logic.
SimpleFormController
SimpleFormController has been deprecated in spring 3.0 .It is the more important controller which has
been used to develop an application.

Whan to use SimpleFormController?


There are some characteristics available for a request then only we can use SFC.
1. If a request contains data
2. There is a request wrapping
3. Along with that Form Handling is there then only we can use SFC

Why it is called SimpleFormController ?


In general if we want to display static page we going to use parameterizableViewController or
UrlFileViewController and for dynamic page we can use AbstractController.
Means we going to deals with multiple controller to perform the above tasks but SFC is the controller
which help the programmer to render static page as well as dynamic page means it’s very simple for the
programmer to work.
In SFC there are two request considered
1.Initial phase request (GET)
2.Postback phase request (POST)
If we want form handling means we have to use spring tags in this controller.

Why we have to use Spring provided tags?


Upon requesting SFC will going to render the formview to the user.
After rendering user can fill that form and returns to SimpleFormController with same url patterns, But
user may forget to fill some data or he has written some invalid data after validating we have to give return
some page to the user will previous entered data along with error message for re-entering or re-correcting .
So using normal HTML or jsp page we can’t perform such operation and logic because of that spring
came up with their own tag library .
It internally going to converted into normal html tags only.
Whole dealing with form data rendering one more component is important i.e. command class object
which help in rendering the data.
While writing the form tag we have to give the commandName for form data rendering by default
command Name is command.
How the Spring Form looks like ?
Its same as HTML only just prefix form. We have to import a one tag we have to use spring tags.
There are almost all the tags are available in spring tag library.
Internals of SimpleForm controller
Example#1 (Show the Static form page and add the criteria)

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.

Form Validation in SimpleFormController

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.

BindException(C) implementation of (Binding Result and Errors)


While dealing with Simpleform controller we come across the class called BindException.
Actually BindException is class used for Handling the Exception across the application.
BindException class implements two interfaces i.e Errors and BindingResult.
Both interface plays different role while dealing with Bind Exception .Actually BindingResult used by
Abstract class internally to Bind internal Exception .

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…

Important Possible return types to a controller


1. Void
2. String
3. ModelAndView
4. Model
5. ModelMap
6. Map
7. View etc…
@ModelAttribute:
Use @ModelAttribute base on parameter in handler method of controller class to specify the command
class and its object to perform request wrapping.
@ModelAttribute is multipurpose annotation expose any data to to web view. Suppose I want to render
a view page with master data that is coming from data base in this case I have to write a method which
returns master data to render in view page and I have to annotate that method with @ModelAttribute.

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.

Benefits of Using ORM

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

Integrated With Hibernate

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.

We can use Factory Beans like “LocalSessionFactoryBean” or “AnnotationSessionFactoryBean”


classes as beans to create sessionFactory Object by supplying Hibernate Configuration Properties of
Hibernate Configuration File or Mapping Annotations based Domain class and also DataSource 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.

Security (authentication + authorization)


Checking the identity of the user is called authentication.
Checking the access permission of the user is called authorization.
Provide the authorization /access permission not based on user name ,provide them based on roles.

How to Secure our application?


By default Security is not enable .We need to implement the security for an application for securing of our
resource of our application.
First we need :
Authentication Store :
Authentication store may be LDAP Server ,DB or file where we need to store user information like
username ,password and the role of the user .
We should able to access the credential within the authentication store and should able to validate in
the authentication store.
So we need Some component For accessing the data from the authentication store, thats why
authentication Provider will be there.
For every security mechanism it could be j2ee,it could be spring or it could be our custom security
.Everyone has to implement the component in this way .This could be the final architecture of the security
.
So Authentication Provider will access the authentication information to the Authentication Store and
passes the data to Authentication Manager.
Authentication Provider will access the authentication information to the Authentication Store and
passes the data to Authentication Manager User details like username, password and role of user pass to
Authentication Manager .
Authentication manager will have 2-task one is
Authentication
Authorization
Both the aspect will manage by Authentication Manager Whenever the user will try to log in to the
application, Whenever the user will try to submit the request to the login.jsp by entering the username and
password the request comes to LoginServlet.java .
Filter will check user is login or not? If not logged in again the request is comes to logging again filter
will come again it will forward.
So filter should not be applied in login.jsp and LoginServlet.java.Without login user should be access
login.jsp and LoginServlet.java
Now the user fist enter the user name and password in the login.jsp and enter the submit .
Then The request is comes to LoginServlet.java. The LoginServlet takes the username and password
and goto Authentication Manager, asking whether the current user apply name of username and password
is valid or invalid?
If it is invalid throws an exception and if it is valid takes the user details of the user representing the role
of the user will return to the loginServlet .
Then Login Servlet has to maintain the authentication information of the current user who is accessing
the system in the session level .
In the LoginServlet it has to create one session .
The current user who is accessing the system and it should be placed to the logged in user details object
in to the session and forward the user to the home page.
Whenever the user is trying to access any of the resource of our application request will comes to whom
Authentication Filter.

What does the Authentication Filter will do?


Authentication filter will not check the incoming request takes the request and goes to the session
.Checks session is there or not there ? User is logged in user or not logged in user it will check first? Rather
It will check what is the resource the user is trying to access how by going to resource-autherity.xml check
the resource is the user is trying access has authority or anyone can access or not .
That means ammoniums user can access or only authenticated user only will be permit to access first it
will check .
If ammoniums user also can access it will not redirect to login page .it just forward the request to the
corresponding resource .

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 .

Who will Read the data From Authentication Store?


Authentication Provider
Authentication Provider will not validate he will take the user information and pass to other class
within our application.

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.

What does my Authenticate manager will do?


The authenticate manager will compare the user details with login user.
If it is valid then it take the role of the user once it is identify role of user then it is going to the
configuration file resource-authority.xml which resource can access by which authorization role user has
to configure by the programmer .
What are the resources are there in our system, and there resources are access by which role user will
configure by us .
Which is not automatic which is manually configure because i am the owner i am deciding which page
is accessing by whom.

In non Spring environment we can implement security .


JavaEE Web security
Here Authentication Manager and Authentication Provider work will be taken care by
servletContainer based on the configuration in web.xml to reduce border on programmer .
But there are some limitations
1. Web.xml entries are not portable across the multiple servers.
2. Some web server don’t support this model.
3. Going to commercial Application server only for security model is very cost effective.
4. Some server don’t support LDAP server as authentication store.
To overcome this problem use spring security comes into picture
1. It run in all the servers and works irrespective they support security or not.
2. Support all the model and authentication Stores
3. It is also declarative security model.
4. Can be applied for normal web application and Spring MVC web applications.
Note

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” .

We need Spring security jars of

Spring-security-3.0.5 RELEASE.jar contains

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

You might also like