DIR Return Create A Forum - Home
---------------------------------------------------------
Java
HTML https://java.createaforum.com
---------------------------------------------------------
*****************************************************
DIR Return to: General Discussion
*****************************************************
#Post#: 10--------------------------------------------------
SPRING MVC BASICS
By: shekar Date: January 30, 2015, 4:03 am
---------------------------------------------------------
Spring MVC Framework
Model view controller is a software architecture design pattern.
It provides solution to layer an application by separating three
concerns business, presentation and control flow.
Model contains business logic, controller takes care of the
interaction between view and model.
Controller gets input from view and coverts it in preferable
format for the model and passes to it. Then gets the response
and forwards to view.
View contains the presentation part of the application.
DispatcherServlet:
In Spring MVC , the core disatcher component is the
“DispatcherServlet“, which act as the front-controller (design
pattern). Every web request have to go through this
“DispatcherServlet“, and the “DispatcherServlet” will dispatches
the web request to suitable handlers.
This class is a front controller that acts as central dispatcher
for HTTP web requests.
Based on the handler mappings we provide in spring
configuration, it routes control from view to other controllers
and gets processed result back and routes it back to view.
Control Flow in Spring MVC
1.
servlet container to a front controller (DispatcherServlet).
2.
request to matching controller.
3.
to front controller (DispatcherServlet). Generally controller
uses a Service to perform the rules.
4.
to view.
5.
DispatcherServlet.
6.
Spring MVC a Java Model-View-Contraller (MVC) web framework,
which builds on the Spring Inversion of control(IoC) framework,
extensive use of the Spring’s features make the Spring MVC
framework highly decouple the components dependency and simplify
the whole MVC configuration.
The Spring web MVC framework provides model-view-controller
architecture.
And ready components that can be used to develop flexible and
loosely coupled web applications.
The MVC pattern results in separating the different aspects of
the application (input logic, business logic, and UI logic),
while providing a loose coupling between these elements.
The Model encapsulates the application data and in general they
will consist of POJO.
The View is responsible for rendering the model data and in
general it generates HTML output that the client's browser can
interpret.
The Controller is responsible for processing user requests and
building appropriate model and passes it to the view for
rendering.
DispatcherServlet:
The Spring Web model-view-controller (MVC) framework is designed
around a DispatcherServlet that handles all the HTTP requests
and responses.
The request processing workflow of the Spring Web MVC
DispatcherServlet:
Following is the sequence of events corresponding to an incoming
HTTP request to DispatcherServlet:
1.
the HandlerMapping to call the appropriate Controller.
2.
service methods based on used GET or POST method. The service
method will set model data based on defined business logic and
returns view name to the DispatcherServlet.
3.
pickup the defined view for the request.
4.
model data to the view which is finally rendered on the browser.
All the above mentioned components ie. HandlerMapping,
Controller and ViewResolver are parts of WebApplicationContext
which is an extension of the plain ApplicationContext with some
extra features necessary for web applications.
Configuration:
Step1:
We need to map requests that you want the DispatcherServlet to
handle, by using a URL mapping in the web.xml file.
In web.xml primarily we are doing servlet mapping to give
configuration for DispatcherServlet to load-on-startup and
defining spring configuration path.
Example:
<web-app id="WebApp_ID" version="2.4"
xmlns="
HTML http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="
HTML http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
HTML http://java.sun.com/xml/ns/j2ee
HTML http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<servlet-mapping> tag indicates what URLs will be handled by the
which DispatcherServlet. Here all the HTTP requests ending with
.jsp will be handled by the HelloWeb DispatcherServlet.
The web.xml file will be kept WebContent/WEB-INF directory of
your web application.
Step2:
Initialization of HelloWeb DispatcherServlet, the framework will
try to load the application context from a file named
[servlet-name]-servlet.xml(HelloWeb-servlet.xml) located in the
application's WebContent/WEB-INF directory.
<beans xmlns="
HTML http://www.springframework.org/schema/beans"
xmlns:context="
HTML http://www.springframework.org/schema/context"
xmlns:xsi="
HTML http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
HTML http://www.springframework.org/schema/beans
HTML http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
HTML http://www.springframework.org/schema/context
HTML http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint" />
<bean
class="org.springframework.web.servlet.view.InternalResourceView
Resolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
Controller:
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC
Framework!");
return "hello";
}
}
Sample Application:
Spring Controller
Spring comes with many Controllers, normally, you just need to
extend the AbstractController, if you do not have other special
requirement, and override the handleRequestInternal() method and
return a ModelAndView object.
Example:
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest
request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("msg", "hello world");
return model;
}
}
1.ModelAndView(“hello”) – The “hello” will pass to Spring’s
viewResolver later, to indentify which view should return back
to the user.
2. model.addObject(“msg”, “hello world”) – Add a “hello world”
string into a model named “msg”
View (JSP page)
In this case, “view” is a jSP page, you can display the value
“hello world” that is store in the model “msg” via expression
language (EL) ${msg}.
Example:
<%@ taglib prefix="c" uri="
HTML http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h1>Spring MVC Hello World Example</h1>
<h2>${msg}</h2>
</body>
</html>
Spring Configuration
In web.xml, declared a DispatcherServlet servlet, named
“HelloWeb “, and act as the front-controller to handle all the
entire web request which end with “htm” extension.
<web-app id="WebApp_ID" version="2.4"
xmlns="
HTML http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="
HTML http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
HTML http://java.sun.com/xml/ns/j2ee
HTML http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
Note:
The DispatcherServlet name “HelloWeb “, is used to defined which
file to load the Spring MVC configurations.
By default, it will look for file by joining the servlet name
“HelloWeb” with “-servlet.xml” as the file name, in this case,
it will find the “HelloWeb -servlet.xml” file and load the
Spring MVC configuration.
Spring Beans Configuration
Declared the Spring Controller and viewResolver.
Example:
<beans xmlns="
HTML http://www.springframework.org/schema/beans"
xmlns:context="
HTML http://www.springframework.org/schema/context"
xmlns:xsi="
HTML http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
HTML http://www.springframework.org/schema/beans
HTML http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
HTML http://www.springframework.org/schema/context
HTML http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="/welcome.htm"
class="com.tutorialspoint. HelloController " />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceView
Resolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
1.
to HelloController class. It means, if an URL with
“/welcome.htm” pattern is requested, it will send to the
HelloController controller to handle the request.
2.
template.
In this case, the controller “HelloController” will return a
ModelAndView object named “hello”, and the viewResolver will
find the file with following mechanism : “prefix + ModelAndView
name + suffix“, which is “/WEB-INF/pages/hello.jsp“.
How it works?
HTML 1.http://localhost:8080/HelloWeb/helloController is requested.
2. URL is end with “/” extension, so it will redirect to
“DispatcherServlet” and send request to the default
BeanNameUrlHandlerMapping.
3. BeanNameUrlHandlerMapping return HelloController to the
DispatcherServlet.
4. DispatcherServlet forward request to the HelloController.
5. HelloController process it and return a ModelAndView object
named “hello”.
6. DispatcherServlet received the ModelAndView and call the
viewResolver to process it.
7. viewResolver return the “/WEB-INF/jsp/hello.jsp” back to the
DispatcherServlet.
8. DispatcherServlet return the “hello.jsp” back to user.
Handler Mapping:
BeanNameUrlHandlerMapping:
In Spring MVC, BeanNameUrlHandlerMapping is the default handler
mapping mechanism, which maps URL requests to the name of the
beans.
If Spring can’t found handler mapping, the DispatcherServlet
will creates a BeanNameUrlHandlerMapping automatically.
Example:
<beans>
<bean name="/helloController"
class="com.tutorialspoint.HelloController" />
<bean
class="org.springframework.web.servlet.handler.BeanNameUrlHandle
rMapping"/>
</beans>
By default, Spring MVC is using the BeanNameUrlHandlerMapping
handler mapping.
ControllerClassNameHandlerMapping:
In Spring MVC, ControllerClassNameHandlerMapping use convention
to map requested URL to Controller (convention over
configuration).
It takes the Class name, remove the ‘Controller’ suffix if
exists and return the remaining text, lower-cased and with a
leading “/”
To enable the ControllerClassNameHandlerMapping, declared it in
the bean configuration file, and now the controller’s bean’s
name is no longer required.
Example:
<bean
class="com.tutorialspoint.HelloController" />
<bean
class="org.springframework.web.servlet.mvc.support.ControllerCla
ssNameHandlerMapping"
/>
</beans>
Spring MVC is mapping the requested URL by following conventions
:
WelcomeController -> /welcome*
HelloGuestController -> /helloguest*
SimpleUrlHandlerMapping:
In Spring MVC application, the SimpleUrlHandlerMapping is the
most flexible handler mapping class, which allow developer to
specify the mapping of URL pattern and handlers explicitly.
Controller:
Controller class to handle the web request.
MultiActionController:
MultiActionController is used to group related actions into a
single controller
Example:
Controller:
ControllerClassNameHandlerMapping configured.
HelloWeb-servlet.xml
InternalPathMethodNameResolver:
The InternalPathMethodNameResolver is the default
MultiActionController implementation to map URL to method name.
the URL will map to the method name in the following pattern :
• /customer/add.htm –> testaddCustomer()
• /customer/delete.htm –> testdeleteCustomer()
Web.xml:
Jsp page(view):
PropertiesMethodNameResolver:
PropertiesMethodNameResolver, a flexible MultiActionController
method name resolver, to define the mapping between the URL and
method name explicitly.
With PropertiesMethodNameResolver, you can map whatever URL name
to corresponds method name easily:
Controller:
Configuration:
The URL will map to the method name in the following pattern :
/customer/add.htm –> add() method
/customer/delete.htm –> delete() method
/customer/hello.htm –> hello() method
Note:
By default, MultiActionController is used the
InternalPathMethodNameResolver to map URL to the corresponds
method name.
ParameterMethodNameResolver:
ParameterMethodNameResolver, a MultiActionController method name
resolver to map URL to method name via request parameter name,
and the parameter name is customizable through the “paramName”
property.
ParameterMethodNameResolver configured, and define the parameter
name thought the “paramName” property
Example:
The URL will map to the method name via the “action” request
parameter name
/customer/add.htm?action=add -> add() method
In general, to return a view or page in Spring MVC application,
you need to create a class, which extends the AbstractController
, and return a ModelAndView() object.
ParameterizableViewController:
The ParameterizableViewController is a subclass of
AbstractController, and return a ModelAndView based on the
“viewName” property
it shows the use of ParameterizableViewController controller to
do a page redirection in the Spring MVC application.
No controller class is required, just declared the
ParameterizableViewController bean and specify the view name
through the “viewName” property.
View Resolver:
Resolve “view name” that returned from the controller class to a
physical view page or JSP page.
InternalResourceViewResolver:
In Spring MVC, InternalResourceViewResolver is used to resolve
“internal resource view” (in simple, it’s final output, jsp or
htmp page) based on a predefined URL pattern.
In additional, it allow you to add some predefined prefix or
suffix to the view name (prefix + view name + suffix), and
generate the final view page URL.
The views under “WEB-INF” folder are named as internal resource
views, as it’s only accessible by the servlet or Spring’s
controllers class.
XmlViewResolver:
In Spring MVC, XmlViewResolver is used to resolve “view name”
based on view beans in the XML file.
Implementation of ViewResolver that uses bean definitions in an
XML file, specified by resource location.
The file will typically be located in the WEB-INF directory;
default is "/WEB-INF/views.xml".
By default, XmlViewResolver will loads the view beans from
/WEB-INF/views.xml, however, this location can be overridden
through the “location” property
Example:
Controller:
A controller class, returns a view, named “WelcomePage“.
XmlViewResolver:
Register the XmlViewResolver in the Spring’s bean configuration
file, loads the view beans from “/WEB-INF/spring-views.xml“.
<bean
class="com.tutorialspoint.WelcomeController" />
<bean
class="org.springframework.web.servlet.mvc.support.ControllerCla
ssNameHandlerMapping"
>
<property name="caseSensitive" value="true" />
<property name="order" value="1" />
</bean>
<bean
class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>
view bean:
The “view bean” is just a normal Spring bean declared in the
Spring’s bean configuration file, where
1.
2.
3.
How it works ?
When a view name “WelcomPage” is returned by controller, the
XmlViewResolver will find the bean id “WelcomPage” in
“spring-views.xml” file, and return the corresponds view’s URL
“/WEB-INF/jsp/WelcomPage.jsp” back to the DispatcherServlet.
ResourceBundleViewResolver:
In Spring MVC, ResourceBundleViewResolver is used to resolve
“view named” based on view beans in “.properties” file.
By default, ResourceBundleViewResolver will loads the view beans
from file views.properties, which located at the root of the
project class path.
However, this location can be overridden through the “basename”
property
Example:
<bean
class="org.springframework.web.servlet.view.ResourceBundleViewRe
solver">
<property name="basename" value="spring-views" />
</bean>
It loads the view beans from “spring-views.properties“, which
located at the root of the project class path.
View Beans:
Declare each view bean as a normal resource bundle style (key &
message), where
1.
2.
3.
Note:
If multiple view resolver strategies are applied, you have to
declare the priority through “order” property, where the lower
order value has a higher priority.
Note
The InternalResourceViewResolver must always assign with the
lowest priority (largest order number), because it will resolve
the view no matter what view name is returned.
It caused other view resolvers have no chance to resolve the
view if they have lower priority.
Spring MVC form handling:
In Spring MVC, form controller is used to handle the form
submission task (binding values to/from Spring’s form tags).
We may just need to extend the SimpleFormController to inherit
the form handling ability.
*****************************************************