The Spring web MVC framework provides model-view-controller
(MVC) architecture. The Spring
framework is designed around a
DispatcherServlet
that dispatches requests to handlers, with configurable
handler mappings, view resolution, locale, time zone and theme resolution as
well as support for uploading files. The
default handler is based on the @Controller
and@RequestMapping
annotations, offering a wide range of flexible handling
methods.
In Spring Web MVC,
DispatcherServlet
class works as the
front controller. It is responsible to manage the flow of the spring mvc
application. The job of the DispatcherServlet
is to take an incoming
URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs)
that combine to form the page or resource that's supposed to be found at that
location.
Use of
DispatcherServlet
:-- Spring’s MVC Inversion of Control is configured in dispatcher-servlet.xml file.
- Any dependency Injection for the beans is also configured in the dispatcher-servlet.xml like ConstructorInjection, SetterInjection.
- Spring MVC provides a feature to initialize and inject the dependencies from the dispatcher-servlet.xml
- ViewResolvers are also configured in dispatcher-servlet.xml
- Predefined tags supported by Spring Framework makes easier for the user to initialize the beans.
The
request processing workflow of the Spring Web MVC DispatcherServlet is
illustrated in the following diagram.
The request processing workflow in Spring Web MVC (high level)
- 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.
The
DispatcherServlet
is an actual Servlet
, and it is
declared in the web.xml
of your web application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
web.xml
After initializing
DispatcherServlet
, framework will try to load the application context from a
file named servlet-context.xml located
in the application's WebContent/WEB-INF/spring/appServlet directory.
Following is the servlet-context.xml file which is located at WebContent/WEB-INF/spring/appServlet :-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--
DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the
Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles
HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves
views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views
directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="edu.constant.code" />
</beans:beans>
servlet-context.xml
The context:component-scan element defines the
base-package where DispatcherServlet will search the controller class.
Here,
the InternalResourceViewResolver class is used for the
ViewResolver.
Implementing
Controllers
There
are two basic annotations used in controller class:-
@Controller
– is used to mark class as controller.@RequestMapping
(value=”/helloworld”, method = RequestMethod.GET) – is used to map the class with specified name.
package
edu.constant.code;
import
java.text.DateFormat;
import
java.util.Date;
import
java.util.Locale;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.stereotype.Controller;
import
org.springframework.ui.Model;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles
requests for the application home page.
*/
@Controller
@RequestMapping("/home")
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by
returning its name.
*/
@RequestMapping(method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
System.out.println("Welcome home!");
Date
date = new Date();
DateFormat
dateFormat =
DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String
formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
/**
* Simply selects the home view to render by
returning its name.
*/
@RequestMapping(value = "/helloworld",
method = RequestMethod.GET)
public String helloworld(Locale locale, Model model) {
logger.info("Welcome hello world! The client locale is {}.", locale);
System.out.println("Welcome hello world!");
Date
date = new Date();
DateFormat
dateFormat =
DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String
formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "helloworld";
}
}
HomeController
Here, there are two
URLs :
View:-
This is the simple
JSP page, displaying the message returned by the Controller. It must be located
inside the WEB-INF/jsp directory for this example only. There are two pages -
home.jsp & helloworld.jsp
Output
of http://localhost:8080/SpringMVCDemo/home - which is home.jsp
Output
of http://localhost:8080/SpringMVCDemo/home/helloworld - which is helloworld.jsp
Download
this spring mvc example from github:-
No comments:
Post a Comment