Basic Spring MVC Framework Tutorial for Beginners

java string concatenationSpring is an open-source framework for the Java platform. The core features are used by Java applications and are used to build web applications on Java EE platform. It provides Model View Controller (MVC) architecture and components that are used to develop loosely coupled web applications. The MVC pattern helps by separating the three modes of application development while providing loose connection between modes. The three modes include input logic, business logic and UI logic.

Learn more about Java Spring through a tutorial at Udemy.com

Spring framework has several modules:

  • Inversion of control: Configurations and management of Java objects
  • Data access: Working with RDBMS on Java and using JDBC.
  • Remote Management: Management of Java objects for remote and local configurations
  • Batch Framework: Spring batch framework is for batch processing that gives reusable functions important for processing large amount of records.
  • Integration Framework: It is an enterprise application integration that gives reusable functions, which proves to be important in messaging and in event driven architectures like routers and transformers. It supports filter and pipe-based architectures.

The Model contains the application information and consists of POJO. It notifies you about the change in state to its associated views and controllers.

The view renders the information sent by the model. Basically, it generates HTML files as output that is interpreted by client browsers. The controller acts as a mediator between the view and model. It updates the model’s state and tells the view to render the model’s information. The spring web Model View Controller (MVC) framework is created around DispatcherServlet that handles a sequence of events, which occur corresponding to incoming HTTP requests and responses. The flow of information is as follows:

  • After receiving an HTTP request, DispatcherServlet consults HandlerMapping to call the appropriate controller.
  • The controller then takes the request and calls the respective service methods. The service methods return the appropriate view name to the DispatcherServlet on the basis of defined business logic.
  • The DispatcherServlet will then ask ViewResolver to give it a defined view based on the request
  • Once the view is selected, DispatcherServlet passes the model information to the view, which is rendered in the browser.

Interested to learn more about Java Spring? Take up a tutorial at Udemy.com

Spring Configuration:

A web.xml file is used for URL mapping to make DispatcherServlet handle requests.

<web-app id=“Spring_ID" 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">

<display-name>Spring MVC Framework</display-name>

<servlet>

<servlet-name>Hello_world</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>Hello_world</servlet-name>

<url-pattern>*.jsp</url-pattern>

</servlet-mapping>

</web-app>

On initialization of Hello_worldDispatcherServlet, the framework will load the applications from a file “hello_world-servlet.xml” in this example.

The servlet-mapping maps the DispatcherServlet and all the “.jsp” requests will be handled by DispatcherServlet.

To change the location of the default servlet.xml file name and its location, you add a ContextLoaderListener.

Web App Configuration

<web-app...>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/Web-INF/Hello_world-servlet.xml</param-value>

</context-param>

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

</web-app>

Now we can check configuration for Hello_world-servlet.xml file. Springs Bean Configuration detects and initializes beans.

Spring Bean Configuration

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

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

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scanbase-package=“spring_learn_mvc” />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>

Points to note for hello_world-servlet.xml file are:

  • It is used to create beans and override the definition of any beans with the same name in global scope.
  • The context component tag is used to activate Spring MVC annotation scanning capability, which allows usage of annotation like @RequestMapping and @Controller.
  • The InternetResourceViewResolver resolves view names on basis of defined rules.

DispatcherServlet request the controllers to execute the functionality assigned to it. ”@Controller” is an annotation that defines the class functioning like a controller.”@RequestMapping” maps a URL of the entire class or particular handler.

Defining Controller

@Controller

@RequestMapping("/helloworld”)

public class HelloController{

@RequestMapping(value=“/hello”,method = RequestMethod.GET)

public String printHello(ModelMap model) {

model.addAttribute("message", "Hello World Spring MVC Framework!");

return "helloworld”;

}

}

The value parameter indicates that the URL to which handler is mapped; and method parameter handles HTTP request.

Things to note:

  • The business logic is defined inside the service method.
  • Based on the business logic, a model is created inside the method. You can set various attributes to the model and these attributes are accessed by the view.
  • Define service method returns strings containing the name of the views that will be used.

Creating the JSP Views

Many types of views are supported by Spring MVC for instance HTML, JSPs and PDF.

<html>

<head>

<title>Hello Spring MVC Framework</title>

</head>

<body>

<h2>${message}</h2>

</body>

</html>

“$message” is the same attribute that was created in the controller.

Steps to build the Hello World Application in Spring MVC Framework:

  • Create web project, give a name “helloworld” and create package “myfirstapp” under src folder.
  • Drag and drop the spring libraries on to the WebContent/WEB-INF/lib folder.
  • Create a Java class “HController” under the same package.
  • Create Configuration files like Web.xml and “helloworld-servlet.xml” inside the folder WebContent/WEB-INF.
  • Create a subfolder inside the folder WebContent/WEB-INF. Create view file helloworld.jsp inside the subfolder.
  • Finally create all the configuration and source files and export application.

Example Hello World to MVC

Lean Java from scratch through a tutorial at Udemy.com

HController.java file

package myfirstapp;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.ui.ModelMap;

@Controller

@RequestMapping("/helloworld")

public class HController{

@RequestMapping(method = RequestMethod.GET)

public String printHello(ModelMap model) {

model.addAttribute("message", "My first Spring Framework !");

return "helloworld";

}

}

Spring configuration file web.xml file:

<web-app id="Web_ID" 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">

<display-name>Spring MVC  Framework 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>

Spring web configuration helloworld-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

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

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="myfirstapp" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

</beans>

The hello.jsp file

<html>

<head>

<title>Hello World my First MVC</title>

</head>

<body>

<h3>${message}</h3>

</body>

</html>

Import the source and configuration files and export the application. Save the application in war file option in local host server folder.

Benefits of Spring usage:

  • Enterprise class applications can be developed using POJOs. The benefit is that we don’t need enterprise Java beans container such as application servers but the option to use servlet container is present.
  • Spring follow modular approach. We only have to handle packages that are required by us.
  • Testing of application becomes easy as technology dependent code is moved into the framework. POJO makes it easier to utilize dependency injection for test data injection
  • Spring framework has lightweight containers. This makes the process of developing and deploying applications very robust.
  • Spring provide excellent API to translate technology specific exceptions into consistent, unchecked exceptions.
  • Provide consistent management interface that can scale up and down transactions.