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

Developing a Web Application with Spring Boot and Spring MVC

In this article we will show how to develop a web application with Spring MVC and Spring Data using also Spring Boot with Maven to the configuration, which greatly facilitates the development of this type of application

Spring Boot is a tool for the development of applications using Spring framework without requiring virtually no configuration. Spring Boot is able to identify what the main characteristics of the application being developed and automatically make the necessary settings, for example, the applicationContext.xml file, web.xml and data sources. It developers earn much in productivity, focusing only on the development of the application and not the configuration of the used tools and frameworks, which are repeated in almost all projects.

Spring has always been known to be a robust and comprehensive framework, but needs different settings. However, version version the tool is improving this feature. Initially, the entire configuration of Spring was done with XML files, but in version 2.5 the notes have been introduced so that it was made directly in the code, eliminating much of the XML files, greatly facilitating the configuration of applications. Now with Spring Boot, the idea is that virtually no configuration is required, even with annotations in the code.

It has four main components to perform the functions described above:

  1. Automatic Configuration: Spring Boot automatically identifies the settings required by the type of application, for example, if a Web application with JPA or Rest API;

  2. Automatic Dependencies: Spring Boot adds, the type of project, a set of libraries that have been tested together, reducing compatibility issues;

  3. Command Line Interface: provides a command line interface where the programmer can easily, create, execute and modify an application;

  4. Actuator: It is a tool that allows the programmer to check what is going on internally in an application with Spring Boot.

In this article we will show how to configure the application using the settings and automatic dependencies Spring Boot to create a web application quickly and easily and with virtually no configuration required. Technically, we will build an application with Spring MVC framework, Spring Data JPA to make the persistence of data, the H2 database that is already in the default installation of Spring Boot and Thymeleaf to define views. The latter is a template engine that replaced the JSP.

Application Development

It will be developed a simple application, only to demonstrate the Spring Boot functionality will be developed and, therefore, it will have a list of books that will be organized by the author's name. There will be a page for each of these where their respective list of books and a form which will allow the registration of new books for this author is displayed. The application of this article was developed using the Eclipse IDE, but any IDE can be used.

For the application configuration was used Apache Maven (Spring Boot also supports Gradle), to this were added four dependencies of the same:

  • Spring-boot-starter-web, which adds dependencies Spring MVC;

  • Spring-boot-starter-data-jpa, adding dependencies Spring Date;

  • Spring-boot-starter-thymeleaf, which adds the thymeleaf dependencies for the development of vision, and;

  • the com.h2database, which is the database that will be used in this application.

Listing 1 shows the code of the pom.xml file with the added dependencies.

Listing 1. pom.xml for the application configuration with Maven

<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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.mrbool.mvc</groupId>
        <artifactId>calendar</artifactId>
        <version>0.0.1-SNAPSHOT</version>
   
        <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>1.3.1.RELEASE</version>
        </parent>
   
        <dependencies>
              <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
              <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-jpa</artifactId>
              </dependency>
              <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-thymeleaf</artifactId>
              </dependency>
              <dependency>
                    <groupId>com.h2database</groupId>
                    <artifactId>h2</artifactId>
              </dependency>
              <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-test</artifactId>
                    <scope>test</scope>
              </dependency>
        </dependencies>
   
        <build>
              <plugins>
                    <plugin>
                          <groupId>org.springframework.boot</groupId>
                          <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
              </plugins>
        </build>
   
  </project>

The tag in the file indicates which version of Boot Spring will be used in the project, and thus all Spring Boot libraries also use this version. Verify that the tag of the three libraries Spring Boot (spring-boot-starter-web, spring-boot-starter-data-jpa, spring-boot-starter-thymeleaf) are not versions added because they all use the version that was defined in the tag.

With the configured application, the first step in the development was the implementation of the class that represents the objects that will be persisted in the database, which is the Book class. This class has several notes of the JPA, as @Entity to indicate that the class is a database entity, @Id to indicate that the id field is the entity identifier, the @GeneratedValue indicating that the value is generated database and @Column to set some parameters of the columns as the name, if it can receive null values or if the column value is unique. Listing 2 shows the Book class code with your notes.

Listing 2. Class Book with JPA annotations

 package com.mrbool.mvc.entity;
  
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 
  
 @Entity
 public class Book {
 
  
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Long id;
 
  
     @Column(name = "title", nullable = false)
     private String title;
 
  
     @Column(name = "isbn", nullable = false, unique = true)
     private String isbn;
 
  
     @Column(name = "author", nullable = false)
     private String autor;
 
  
     @Column(name = "description", nullable = true)
     private String description;
 
  
     public Long getId() {
         return id;
     }
     public void setId(Long id) {
         this.id = id;
     }
     public String getTitle() {
         return title;
     }
     public void setTitle(String title) {
         this.titulo = title;
     }
     public String getIsbn() {
         return isbn;
     }
     public void setIsbn(String isbn) {
         this.isbn = isbn;
     }
     public String getAuthor() {
         return author;
     }
     public void setAuthor(String author) {
         this.autor = author;
     }
     public String getDescription() {
         return description;
     }
     public void setDescription(String description) {
         this.description = description;
     }
 
  
 }

Using the H2, the database will always be created when the application is run, which facilitates the development because no initial configuration is required to use the application. For simplicity, this article will use the H2 even though Spring Boot works with any database that has a JDBC driver.

Using Spring Data JPA you can create a repository for the book class: This is an interface that contains several pre-implemented methods for handling data of an entity as methods to save, delete, list and retrieve the Class ID. To create this interface simply extend the JpaRepository interface; past types are used the entity class (in this case the paper grade) and type of attribute that is the identifier of this class (which in this case is a long).

In addition, the programmer can create several specific methods of search, just follow the naming standard methods such as, findByNameAtributte. Listing 3 shows the code of this interface.

Listing 3. Class repository Book entity

package com.mrbool.mvc.repository;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

import com.mrbool.mvc.entity.Book;

public interface BookRepository extends JpaRepository <Book, Long> {

 /**
  * Find all the books by the same author..
  *  
  * @param author
  * @return list of books
  */
 List <Book> findByAuthor(String author);

 /**
  * Find a book from its title.
  * Returns a list because there can be
  * More than a book with the same title  
  * @param title
  * @return list of books
  */
 List <Book> findByTitle(String title);

 /**
  * Find a book from your isbn, like isbn is unique, only one book can be found.  
  *  
  * @param isbn
  * @return livro
  */
 Book findByIsbn(String isbn);

}

All of which were added three new methods to search:

  • one to fetch the books by the author;

  • one to find the books by title and;

  • one to find the book by its ISBN.

The Controller class is quite simple, first @Controller annotation is added to indicate that the class is a controller, and @RequestMapping note, indicating the way to access this driver. A BookRepository type attribute is added, which is the repository created in Listing 3, where the actual Spring will make the injection of this dependence. In addition, there are two methods: one to list the books of a particular author and that will be accessed when the request for this controller is the GET type, and the method for adding a book, which will be accessed when the request is POST type. Listing 4 shows the code for this class.

Listing 4. Controller of the Book class

 package com.mrbool.mvc.controller;
     
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.stereotype.Controller;
   import org.springframework.ui.Model;
   import org.springframework.web.bind.annotation.PathVariable;
   import org.springframework.web.bind.annotation.RequestMapping;
   import org.springframework.web.bind.annotation.RequestMethod;
     
   import com.mrbool.mvc.entity.Book;
   import com.mrbool.mvc.repository.BookRepository;
     
   import java.util.List;
     
   @Controller
   @RequestMapping("/")
   public class BookController {
          
         private BookRepository bookRepository;
     
         @Autowired
         public BookController( BookRepository bookRepository) {
               this.bookRepository = bookRepository;
         }
     
         @RequestMapping(value = "/{author}", method = RequestMethod.GET)
         public String listBooks(@PathVariable("author") String author, Model model) {
               List<Book> listBooks = bookRepository.findByAuthor(author);
               if (listBooks != null) {
                     model.addAttribute("books", listBooks);
               }
               return "listBooks";
         }
     
         @RequestMapping(value = "/{author}", method = RequestMethod.POST)
         public String addBookAuthor(@PathVariable("author") String author, Book book) {
               book.setAuthor(author);
               bookRepository.save(book);
               return "redirect:/{author}";
         }
   }

The listBooks method is quite simple, because it will be accessed when the request for this controller is the type GET and receive as parameter the name of an author, where is made a search in the database to find all the books of this author. If books are found, this list is added to the model to be displayed after the application of the screen, which will be shown in the next listing.

The addBookAuthor method is similar to the previous one, because it will be accessed when the request to the controller for POST type and also receives as a parameter the name of an author. The difference is that, in addition, he must also receive data from a book, which will be done by a form, which will also be shown in the next listing. The book sent by the request will be registered in the database using the repository interface. Finally, this method redirects to the listbooks method, and the book that has just been registered is already displayed on the screen.

With all classes to access and integration of data, just create the vision and it was created listaLivros.html file in src/main/resources/templates. This screen has two parts, the first being a list of the author's books that was recovered from the access URL, which should be made in the format http://localhost:8080/nameAuthor. If there is no registered book to the author will be shown the text "No book Joined to this author," otherwise it will be shown the book list. The second part of the screen is a registration form books with the Title data, ISBN and description, and the author is registered with the author's name of the accessed page. Listing 5 shows the code of this screen.

Listing 5. Vision for the registration and listing of Books

 <html>
   <head>
   <title>Reading List</title>
   </head>
   <body>
         <h2> Books List by Author </h2>
         <div th:unless="${#lists.isEmpty(books)}">
               <dl th:each="book : ${books}">
                     <dt class="bookHeadline">
                           <span th:text="${book.title}">Title</span> by <span
                                 th:text="${book.author}">Author</span> (ISBN: <span
                                 th:text="${book.isbn}">ISBN</span>)
     
                     </dt>
                     <dd class="bookDescription">
                           <span th:if="${book.description}" th:text="${book.description}">Description</span>
                           <span th:if="${book.description eq null}"> No description has been added to this book!</span>
                     </dd>
               </dl>
         </div>
         <div th:if="${#lists.isEmpty(books)}">
               <p> No Book Joined to this author </p>
         </div>
         <hr />
         <h3> Add a new book to the author::</h3>
         <form method="POST">
               <label for="title">Title:</label> <input type="text" name="title" size="50"></input><br />   
               <label for="isbn">ISBN:</label> <input type="text" name="isbn" size="15"></input><br />  
               <label      for="description">Description:</label><br />
               <textarea name="description" cols="80" rows="5"> </textarea>
               <br /> <input type="submit"></input>
         </form>
   </body>
   </html>

Finally, you must create a class that initializes the application with Spring Boot and creates the database H2 and Apache Tomcat. The only configuration required in this file is to say which are the entities, repositories and drivers (if everything is in the same package it is not necessary). Listing 6 shows the code for this class.

Listing 6. Class that starts the application

 package com.mrbool.mvc.application;
     
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.boot.orm.jpa.EntityScan;
   import org.springframework.context.annotation.ComponentScan;
   import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
     
   @SpringBootApplication
   @EntityScan(basePackages = { "com.mrbool.mvc.entity" })
   @EnableJpaRepositories(basePackages = { "com.mrbool.mvc.repository" })
   @ComponentScan(basePackages = {"com.mrbool.mvc.controller"})
   public class Application {
         public static void main(String[] args) {
               SpringApplication.run(Application.class, args);
         }
   }

To run the application in Eclipse just run the Application class and wait for Tomcat to boot. Once that happens, access from any browser to http://localhost:8080/nameAuthor. It will show the screen of the developed application. Initially the list of books will be empty, but you can register as many books as you want using the form that is at the bottom of the screen. Figure 1 shows an example application running, see which can be registered books for this.

This article shows how to develop a simple application with Spring Boot using the frameworks Spring Date and Spring MVC. This application was not required virtually no configuration or database or XML files and virtually any configuration note. This is the great goal of Spring Boot, which allows the programmer to focus only on the development of the functional requirements of the application, avoiding repetitive work that are required for all projects.

I hope you liked the article and that it is useful! See you!

Links

Official website of Spring Boot with tutorials and more examples

http://projects.spring.io/spring-boot/

Official website of Spring Date

http://projects.spring.io/spring-data/

Official Spring MVC page

https://spring.io/guides/gs/serving-web-content/



Web developer and passioned for web design, SEO and front end technologies.

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