Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Spring MVC Framework: Mapping the DispatcherServlet

See in this article an introduction to the framework that works with @Controller and @RequestMapping annotations for handling requests. Also we will see one of the ways of mapping the DispatcherServlet.

The MVC design pattern is one of the most used in programming, however, Java this standard was implemented practically in the hand or with the use of small frameworks. How was something that took a lot of work and worked very well in other languages, then soon the community received the Struts and other frameworks to create applications with the three layers: model, view and controller.

The Spring Framework MVC is a MVC web framework developed by Spring Source and open source. It is designed around a Servlet, the DispatcherServlet that dispatches requests to controllers. A standard controller Spring MVC makes use of @Controller and @RequestMapping notes, which offer a wide range of flexible features for handling requests.

Controllers Spring MVC

Controllers Spring MVC give access to part of the application which is usually responsible for resolving issues related to business logic and are usually referred to as service interfaces. The DispatcherServlet directs user requests to the controllers according to the mapping carried out in the latter. These controllers interpret user input (requests) and turn it into a model in Spring MVC is represented by Interface Model and its implementations. The Spring implements a controller in a very abstract way, allowing you to create a wide variety of controllers. In Spring 2.5 was introduced a programming model based on annotations for MVC controllers such as, for example, @RequestMapping, @RequestParam, @ModelAttribute.

The @Controller and @RequestMapping annotations

The @Controller annotation indicates that a particular class serves as a controller, acting as a stereotype for the annotated class, indicating its role. Already @RequestMapping annotation is used to map URLs like www.DNS_ofthe_aplication/client to a whole class or a particular handler method. Usually the class level annotation maps a specific requests path in a form controller, with additional notes on method level, narrowing the primary mapping for a specific HTTP request method ("GET", "POST", etc. ) or an HTTP request parameter condition.

An example of the use of @Controller and @request notes will be shown in Listing 1, where @Controller annotation indicates that the Customer class is a Spring MVC controller. Thus, the DispatcherServlet can forward user requests to be handled in this class.

Listing 1. Using notes

package com.mrbool.controller;
  import org.springframework.stereotype.Controller;
  import org.springframework.ui.Model;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
   
  @Controller
  @RequestMapping(value = "/client")
  public class Client {
   
      @RequestMapping(method = RequestMethod.GET)
      public String showAllClients(Model uiModel) {
          // ...
          return "page";
      }
   
      @RequestMapping(method = RequestMethod.POST)
      public String persistNewClient(Model uiModel) {
          // ...
          return "page";
      }
  }

The @RequestMapping annotation indicates that the controller, which in this case is the Customer class, you will receive the requests made to the URL www.DNS_ofthe_aplication/client. The showAllClients method is also noted with @RequestMapping note, indicating that this method will receive the requests made to URL www.DNS_ofthe_aplication/client whenever it is an HTTP GET request.

In turn, the method persistNewClient receive requests made URL www.DNS_ofthe_aplication/client using the POST method. This criterion is defined by using the method parameter @RequestMapping note. A method mapped to the @RequestMapping annotation must have a return that, in turn, will be displayed to the user. This return can be of various formats: hypertext page, a file (XML, JSON, JPEG, PDF), among others. When it comes to pages that will be displayed to the user, they should be treated by any ViewResolver, we will see in the next section.

ViewResolver

The return of a method annotated with @RequestMapping should be treated for some ViewResolver. This allows the developer to render models of web pages in a browser without tying it to a specific technology. It should be set in the context of DispatcherServlet. There are many options for ViewResolvers that can be used in Spring MVC: one is the integration with Apache Tiles project. In this work it will be used a Spring MVC ViewResolver: the InternalResourceViewResolver.

Recalling that the Apache Tiles allows you to define page fragments that can be assembled into more full pages at runtime. Such fragments or tiles can be used to reduce duplication of page elements into other tiles to develop reusable templates.

Spring MVC configuration

The configuration of Spring MVC is focused on web.xml and DispatcherServlet context configuration. As the Spring MVC is designed around a Servlet, the DispatcherServlet, this needs to be recorded and mapped in the web.xml file. Already the DispatcherServlet context configuration can be done in an XML file. This file must be loaded with the application. Therefore, it is necessary to indicate in the web.xml file of the project that the Spring configuration file must be loaded. This is not the only way to configure DispatcherServlet context, but is the form used in this work. In the documentation (section Links) You can find more information, noting that the form seen here is the most recommended.

Creation and project setup

The project-example created in this article has only teaching purposes, therefore will use a simple scenario, you will use a small part of the resources of the Spring Framework MVC.

The first thing to do is to create a Java web project using Maven (see Links section). The name given to the project was developed "spring-mvc". The Spring Tool Suite (STS) tool was used to develop the project in question, but any Java IDE (Eclipse, NetBeans, etc.) can be used to recreate this example. The STS can be used both on machines with Windows, Linux or MAC. Your environment is based on Eclipse and provides a complete environment for development.

Apache Tomcat (Links section) was chosen to be the software web container of this application, despite the STS Pivotal count, which is the replacement Tomcat in Spring.

Pom.xml configuration file

The pom.xml file should contain two dependencies of the Spring Framework and the dependencies for the use of Servlet, JSP and JSTL, as shown in Listing 2.

Listing 2. Dependencies List

spring-context
  spring-webmvc
  servlet-api
  jsp-api
  jstl

Thus, in Listing 3 shows the pom.xml configuration.

Listing 3. pom.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mrbool</groupId>
        <artifactId>spring-mvc</artifactId>
        <version>1.0.0-BUILD-SNAPSHOT</version>
        <name>spring-mvc</name>
        <packaging>war</packaging>
   
        <dependencies>
              <!-- Spring -->
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
   
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-webmvc</artifactId>
                    <version>4.2.4.RELEASE</version>
              </dependency>
              <!-- Servlet -->
              <dependency>
                    <groupId>javax.servlet</groupId>
                    <artifactId>javax.servlet-api</artifactId>
                    <version>3.1.0</version>
              </dependency>
              <dependency>
                    <groupId>javax.servlet.jsp</groupId>
                    <artifactId>jsp-api</artifactId>
                    <version>2.1</version>
                    <scope>provided</scope>
              </dependency>
              <dependency>
                    <groupId>javax.servlet</groupId>
                    <artifactId>jstl</artifactId>
                    <version>1.2</version>
              </dependency>
        </dependencies>
        <build>
              <plugins>
                    <plugin>
                          <groupId>org.apache.maven.plugins</groupId>
                          <artifactId>maven-compiler-plugin</artifactId>
                          <version>3.3</version>
                          <configuration>
                                <source>1.8</source>
                                <target>1.8</target>
                          </configuration>
                    </plugin>
              </plugins>
        </build>
  </project>

Configuration of the web.xml

The web.xml file is used to perform the configuration of the application servlets. It is required from previous versions to 3.0. In this example it is important to highlight the servlet configuration of Spring MVC: Dispatcher Servlet. He will be responsible for receiving all requests made to the application in question, as is being defined in tag servlet-mapping. Another XML file is passed as a parameter initialization DispatcherServlet: servlet-context.xml, which is the configuration file DispatcherServlet context, as shown in Listing 4.

Listing 4. web.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
   
        <servlet>
              <servlet-name>dispatcherServlet</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <init-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/dispatcherServlet/servlet-context.xml</param-value>
              </init-param>
              <load-on-startup>1</load-on-startup>
        </servlet>
   
        <servlet-mapping>
              <servlet-name>dispatcherServlet</servlet-name>
              <url-pattern>/</url-pattern>
        </servlet-mapping>
   
  </web-app>

Creation and configuration of the DispatcherServlet context

The DispatcherServlet context defines the infrastructure of the processing of requests made to it. This context can be configured via an XML file that should be loaded together with this Servlet. For this, a folder is created with the name "DispatcherServlet" within the WEB-INF directory, inside this folder will create an XML file with the name servlet-context.xml, whose content is the same in Listing 5.

Listing 5. servlet-context.xml Content

<?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">
   
        <annotation-driven />
   
        <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="com.mrbool" />
  </beans:beans>

Driver Creation

Once configured the project is ready to be encoded. In this section you will create a class called controller that will be a Spring MVC controller. To this it should be notes with @Controller and @RequestMapping. The value parameter of @RequestMapping annotation was filled with the "/" character, indicating that this class will meet the requests made to the application root. The home method is also annotated with @RequestMapping and thus, this method will also receive requests handled by DispatcherServlet. As the @RequestMapping annotation value parameter of the home method is not completed, this method will receive the notes from the root of the application to have the GET method. Note the Listing 6 code.

Listing 6. Class Driver

package com.mrbool.controller;
   
  import org.springframework.stereotype.Controller;
  import org.springframework.ui.Model;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
   
  @Controller
  @RequestMapping(value = "/")
  public class Controller {
   
      /**
       * Receives all the request made to the root
       */
      @RequestMapping(method = RequestMethod.GET)
      public String home(Model model) {
          model.addAttribute("message",
                  "My first app using Spring Framework MVC!");
          return "home";
      }
   
  }

The input parameter of the home method is a Model Interface, as Spring MVC Controllers interpret user input (requests) and turn it into a model that is represented by the interface and its implementations. Thus, one can understand that this is a feature of Spring MVC that encapsulates the user request. An Interface Model is also returned to the user.

Note: Model Interface is a model created from a user request, but the mapped with @RequestMapping methods may receive other input parameters such as HttpServletRequest, Locale, etc.

As can be seen in Listing 7, the return of this method is a String. This return should be treated by any ViewResolver, which in this case is the InternalResourceViewResolver and as defined in the servlet-context.xml.

Listing 7. InternalResourceViewResolver

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

Thus, InternalResourceViewResolver defines that the return of the methods annotated with @RequestMapping will be .jsp resources that are in the WEB-INF/views page and have the name that is being returned as the string mapped methods. Note: The default Spring MVC is put .jsp pages in the WEB-INF folder.

Creation of home.jsp page

The page that is returned to the user after the request to www.DNS_ofthe_aplication/client will be created in the WEB-INF/views folder. Before that, the views folder should be created within the WEB-INF folder, following the pattern of the Spring. Then the home.jsp page should be created within the folder views, with the contents of Listing 8.

Listing 8. Page home.jsp

<% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
  <% @ Page session = "false"%>
  <! DOCTYPE html>
  <Html>
  <Head>
  <Title> Spring MVC </ title>
  </ Head>
  <Body>
      <H1> Hello! </ H1>
      <P> nbsp;{message}</P></Body></Html>

The home.jsp page should print to the user attribute "message", which has been set in the Model interface, the home method of the Controller class.

Running the Project

Once configured and set up, it remains only to use Maven for cleaning and project creation. Then, follows the implementation and execution, must access it from the URL http://localhost:8080/juliosouza/.

Imagine creating an application such "arm" today? Increasingly we need time to speed up deliveries and spend time creating layers and the relationships between them.

And what we saw in that article was just a bit of all the structure of the Spring MVC framework. The Container Spring makes it much easier, and we saw this clearly in mapping the DispatcherServlet, which is very flexible, since it can be used with virtually any workflow, provided it has adapted classes.

Links

Spring Framework Reference Documentation: Spring Source 2016: http://docs.spring.io/spring/docs/4.2.4.RELEASE/spring-framework-reference/htmlsingle/

Maven: http://maven.apache.org/

Spring Tool Suite (STS): http://spring.io/tools/sts/all

Tomcat: http://tomcat.apache.org/



Julio is a System analyst and enthusiast of Information Technology. He is currently a developer at iFactory Solutions company, working in the development of strategic systems, is also a JAVA instructor. He has knowledge and experi...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login