Spring Boot - Creating web application using Spring MVC

Introduction :

This section creates a Spring MVC web application using the Spring Boot framework. We will follow the MVC pattern using JSP as the view.

Tools and technologies used for this tutorial are :

  • Spring Boot 1.5.13.RELEASE
  • JDK 1.8
  • Gradle 4.7
  • Eclipse Oxygen

Build with Gradle

Build with Maven

Create a web controller

In Spring’s approach to building web sites, HTTP requests are handled by a controller. You can easily identify these requests by the @Controller annotation. In the following example, the HelloWorldController handles GET requests for '/' and '/welcome' by returning the name of a View, in this case, "index" and "welcome". The Views are responsible for rendering the HTML content:

Create JSP Views

Create index.jsp and hello.jsp files under src/main/webapp/WEB-INF/views folder.

index.jsp
welcome.jsp

Create Application properties

Spring boot load the properties from application.properties or application.yml and add them to the Spring Environment. You can set the properties related to the Spring MVC or static web content in a properties file.

Create an application.properties file under src/main/resources source folder and write the following properties in it.

application.properties

Bootstrap class

To bootstrap Spring MVC application using Spring Boot, create a main class annotated with @SpringBootApplication annotation as follows.

MVCWebApp.java

Run application

Run the MainApp.java class as Java application i.e. go to Run -> Run as -> Java Application

Test the App

Hit http://localhost:8080/ in your browser.

Packaging Spring Boot application as an executable jar/war

You can run the application from the command line with Gradle or Maven. Or you can build a single executable JAR file that contains all the necessary dependencies, classes, and resources, and run that. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you are using Gradle, you can run the application using ./gradlew bootRun. Or you can build the JAR file using ./gradlew build.

If you are using Maven, you can run the application using ./mvnw spring-boot:run. Or you can build the JAR file with ./mvnw clean package.

Running executable jar/war from command line

Use the following command to run the war from the CMD.
>java -jar MVCWebApp-0.0.1-SNAPSHOT.war
or
>java -jar MVCWebApp-0.0.1-SNAPSHOT.jar

Source Code

Complete source code for this example is available at GitHub.

Summary

Hope we are able to explain you Spring Boot - Creating web application using Spring MVC example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Keep visiting TutorialsDesk.com for more tutorials and real time programming examples.
SHARE
    Blogger Comment
    Facebook Comment