Spring MVC Framework

The spring MVC stands for spring Mode View Controller. Spring MVC is a type of design pattern and it helps in separating the business logic and navigation logic. The main components of MVC are,

  1. Controller
  2. Model
  3. View

1)      Controller

The controller manages navigation logic and interacts with the service tier for business logic. The responsibility of controllers is, for receiving the request from the user and calling back end users.

2)      Models

A model helps for encapsulating the application data. This component is a contract between the Controller and View. Model consists of the needed data to render the view and populated by the Controller.

3)      View

This component renders the request to the user with the support of the model object.

All MVC components are configured in the spring ApplicationContext. Intrinsically, all MVC components are configured using Dependency Injection.

Eg: –

<bean id="springCheersController" class="com....web.SpringCheersController">
<property name="methodNameResolver“ ref=“springCheersMethodResolver"/>
<property name="service" ref="service"/>
</bean>

The flow of request in spring frameworks is described in below figure.

Spring MVC
Spring MVC

When a request is sent to the spring MVC framework the following steps happened

  1. In the first step the DispatcherServlet first receives the request.
  2. The DispatcherServlet invokes the controller associated with the request when the DispatcherServlet consults the HandlerMapping.
  3. After the second step the controller process the request by calling the appropriate service methods and returns the ModelAndView object to the DispatcherServlet, this object consists of the model data and the view name.
  4. For finding the actual view to invoke when the DispatcherServlet sends the view name to ViewResolver.
  5. After that the DispatcherServlet will pass the model object to the View to render the result.
  6. In the final step the View with the help of the model data will render the result back to the user.

Eg: – Working of spring framework

Normally we are using the same way as Struts:

Working of Spring MVC
Working of Spring MVC

1)      The DispatcherServlet calls the corresponding Controller, based on the HTTP request URL.

2)      A view is rendered and sent as HTTP response.

Spring Servlet Declaration

We declare Spring DispatcherServlet in ‘WEB-INFO/web.xml’ and map ‘*.html’ URL to it:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
jsp/index.jsp
</welcome-file>
</welcome-file-list>
</web-app>

Spring Servlet Configuration

Now we create the spring configuration file ‘WEB-INF/spring-servlet.xml’.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="springmvc.web.HelloWorldController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property value="org.springframework.web.servlet.view.JstlView"/>
<property value="/jsp/"/>
<property value=".jsp"/>
</bean></beans>
  • Map URL/hello_world.html to controller HelloWorldController.
  • TO declare View Resolver, when view ‘view-name’ is called, the file ‘/jsp/view_name.jsp’ will be used. The view_name is called from the controller.

Controller

After spring configuration it creates Controller ‘WEB-INF/src/springmvc/web/HelloWorldController.java’:

package springmvc.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloWorldController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String aMessage = "Hello World MVC!";
ModelAndView modelAndView = new ModelAndView("hello_world");
modelAndView.addObject("message", aMessage);
return modelAndView;           }
}

This controller calls the view ‘hello_world’, passing ‘message’ to it.

View

Now we create the view ‘jsp/hello_world.jsp’

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<p>This is my message: ${message}</p>
</body>
</html>

Before displaying the message attribute we set in the controller

OUTPUT

Form ‘WEB_INF’ folder

Output
Output

The Framework of the spring web MVC is flexible, robust, and well-designed.

Advantages of spring MVC frameworks are

  1. Easier testing
  2. Bind directly to business objects
  3. Clear separation of roles
  4. Adaptable controller
  5. Simple but powerful tag library
  6. Web Flow
  7. View technologies and web frameworks
  8. Light weight environment

1)    Easy testing

In the most of the spring’s classes are designed as JavaBeans and enable to inject test data using the setter methods. It also provides mock classes to simulate java HTTP objects which makes unit testing of the web layer much simpler. Example of HTTP object is, HttpServletRequest.

2)      Bind directly to business object

We can implement a spring controller interface. Spring MVC does not needed our business model or classes to extend any special classes and this helps you to reuse your business objects by binding them directly to the HTML forms fields. In case your controller classes are the only ones that are required to extend spring classes.

3)        Clear separation of roles

Spring MVC nicely separates the roles played by the different components that make up this web framework.

Eg:- when the concepts such as controllers, command objects, and validators, you will begin to see how each component plays a distinct role.

4)      Adaptable controller

If our application does not require an HTML form, we can write a simpler version of a spring controller that does need all the components required for the form controller. In case, spring gives several types of controllers and each serving variety purpose.

Eg:-   there are no-form controllers, simple form controllers, wizard like form controllers, views with no controllers, and even prepackaged controllers that enable you to write views without your own custom controller.

5)      Simple but powerful tag library

Spring’s tag is small, straightforward and powerful;

Eg: – Spring uses the JSP expression language (EL) for arguments to the <spring:bind> tag.

6)      Web Flow

This module is a subproject and is not bundled with the spring core distribution. It is built on top of Spring MVC and adds the capability to easily write wizard like web applications that span across several HTTP requests

7)      View technologies and web frameworks

Although we are using JSP as our view technology, spring supports other view technologies as well, such as Apache Velocity (jakarta.apache.org/velocity/) and FreeMarker (freemarker.org).This is a powerful concept because switching from JSP to Velocity is a matter of configuration. Furthermore, spring provides integration support for Apache Struts (struts.apache.org), Apache Tapestry (jakarta.apache.org/tapestry), and    OpenSymphony’s WebWork (opensymphony.com/webwork/).

8)      Light weight environment

Spring enables you to build enterprise- ready applications using POJOs, the environment setup can be simpler and less expensive because you could develop and deploy your application using a light weight servlet container.