Skip to main content

Built and Run the example in Spring Boot

In this example, we are using the web-based Spring Initializr interface to generate the package. Here we have added web dependency only to demonstrate the running, building jar/war and understanding build.gradle / pom.xml

Step 1: Open https://start.spring.io to initialize your project with your selected dependencies. Here we are using 'Spring Web', 'Thymeleaf', and 'Spring Boot DevTools' dependencies for the hello world demonstration. 


Now, click on the generate button, it will start downloading a demo.zip file.

Step 2: Extract the downloaded zip in step 1. Import this project to your favorite IDE by navigating the extracted folder path and selecting the pom.xml or build.gradle file, you will get pom.xml when your project is a Maven project and build.gradle if your project is a Gradle project. Here we will be using IntelliJ Idea. 

 

 

Click on OK and follow the instructions with default settings.

On successful importing, you will get the main runner class DemoApplication.java 

	package com.example.demo;

	import org.springframework.boot.SpringApplication;
	import org.springframework.boot.autoconfigure.SpringBootApplication;

	@SpringBootApplication
	public class DemoApplication {

		public static void main(String[] args) {
			SpringApplication.run(DemoApplication.class, args);
		}

	}
    

 

If you selected Maven project then you will get pom.xml file.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

And if you have selected Gradle project then you will get build.gradle file.

plugins {
	id 'org.springframework.boot' version '2.2.6.RELEASE'
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
	developmentOnly
	runtimeClasspath {
		extendsFrom developmentOnly
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

 

Step 3: Now its time to write your application logic. Add a HelloController.java in package com.example.demo.

 

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String helloPage(Model model){
        String s = "Hello World Example";
        model.addAttribute("var1",s);
        return "hello";
    }
}

 Note: Here we have used

          @Controller to make the HelloController Class to behave as a request controller.

          @RequestMapping to name the request URL and hello page is returning String "hello" means Thymeleaf template engine will search for hello.html

file.

Step 4: Add hello.html in resources/templates/  folder.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Spring Boot Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="jumbotron">
        <h1>Spring Boot Tutorials</h1>
        <p th:text="${var1}"></p>
    </div>
    <p><strong>Easytutorials.live</strong> provides simple and comprehensive tutorials on spring-boot, thymeleaf and linux.</p>
    <p>visit  <a href="http://easytutorials.live">easytutorials.live</a> .</p>
</div>

</body>
</html>

 Note: Here we have used html template from w3school bootstrap 4 example.

<p th:text="${var1}"></p> is used to write the object's value inside paragraph tag defined in the helloPage method of HelloController.java 

 

Step 5: Now its turn to run this example by clicking on Run button from IDE or you can run from Termial/cmd, go to the projects directory.

  If you are Linux user and using terminal then run the following command:

     $ ./mvnw spring-boot:run for Maven project

     $ ./gradlew bootRun for Gradle project

  If you are a Windows user and using cmd then run the following command:

     $ mvnw.cmd spring-boot:run for Maven project

     $ gradlew.bat bootRun for Gradle project


Popular posts from this blog

How to Implement AWS RDS Database IAM Authentication in Spring Boot

Amazon RDS for MySQL allows authentication using AWS Identity and Access Management (IAM) database authentication. With this authentication method, you don't need to use a password when you connect to a DB instance. Instead, you use an authentication token. Let us understand how this works? An authentication token is a unique string of characters that Amazon RDS generates on request. Authentication tokens are generated using AWS Signature Version 4. Each token has a lifetime of 15 minutes. You don't need to store user credentials in the database, because authentication is managed externally using IAM. You can also still use standard database authentication. Since IAM authentication tokens are short-lived access tokens that are valid for 15 minutes. For the RDS database this token works as a database password that is required to establish a connection and does not determine how long the existing connection can last. The default value for connection to be alive without activit...

How to upload files in Amazon S3 Bucket using Spring Boot

As stated in the title, we are going to demonstrate that how we can upload and retrieve files from the amazon s3 bucket in spring boot. For this, we must have an account on amazon web services (AWS) . And the next thing you need to have is an IAM user that has programmatic access to the s3 bucket. Follow the steps below to create an IAM user and s3 bucket. Table of Contents 1. Steps to create an IAM user in AWS with S3 bucket full access permission Step 1.1 Login to your AWS account   Step 1.2 Set the user details Step 1.3 Set user permissions Step 1.4 Create a user group and set the access policy Step 1.5 Add user to the group Step 1.6  Set the tags (optional) Step 1.7  Review the user details and permission summary Step 1.8 Download the user credentials 2. See, how to create s3 bucket. Step 2.1 Click on the "Create bucket" button. Step 2.2 Enter the bucket name and select bucket region. Step 2.3 Set file accessibility for bucket items as publi...

Custom Pagination with search and filters in Spring Boot

Every spring boot application is made to manage a large set of data. Also, we need to perform a search and filter the data according to need, And also we cannot load all data in one go on a single page so we need pagination too. In this article, we are going to demonstrate custom pagination with search and filter performed through ajax call. Goal: This demonstration is performed on a set of students' data. We have written a method to generate sample data.   Table of Contents 1. Initialize the project with the following dependencies 2. Set the application properties 3. Create the Student entity 4. Enum to denote the class of student 5. Create JPA repository of entity 6. Create the search & filter command object (CO) 7. Create a data transfer object (DTO) of the Entity for returning the response 8. Create a service for implementing the business login 9. Create a controller 10. Create a utility class for date conversions 11. Create the HTML Data Table design 12. ...

What Is SSL Certificate and how it works?

Deep Dive into SSL Certificate What Is an SSL Certificate? SSL (Secure Sockets Layer) is the common name for TLS (Transport Layer Security), a security protocol that enables encrypted communications between two machines. An SSL certificate is a small data file leveraging this security protocol to serve two functions: Authentication – SSL certificates serve as credentials to authenticate the identity of a website. They are issued to a specific domain name and web server after a Certificate Authority, also known as a Certification Authority (CA), performs a strict vetting process on the organization requesting the certificate. Depending on the certificate type, it can provide information about a business or website's identity and authenticate that the website is a legitimate business. Secure data communication - When SSL is installed on a web server, it enables the padlock to appear in the web browser. It activates the HTTPS protocol and creates a secure connection between th...

How to Implement Spring Security in Spring Boot

Security Example in Spring Boot Implementation of Spring Security in the Spring Boot application is the key point to learn for spring boot developers. Because Authentication and Authorization are the backbones of the whole application. Getting started with the Spring Security Series, this is the first part, in this article we are going to focus on the authentication part with minimal registration. The implementation of registration flow with email verification, customizing password encoding, and setting up password strengths and rules will be explored in another separate article for each.  This article will be the base of the spring security series, the other security features will be explained on the basis of this implementation, so be focused and let's understand. The code contains proper naming & brief comments that makes it very comprehensive. If you feel any difficulty or find any issue, please drop a comment below this post The main goal of this article is to impleme...

How to deploy the Spring Boot application ( jar/war ) on the live server?

There are various methods to deploy the Spring Boot application. In the previous page, we have described how to generate builds (jar/war) by Maven/Gradle. In this article, we will describe the built deployment process. So before we begin deploying spring boot applications that are built in either jar or war, we need to understand what are the differences between them, both can be built using any of the built tools Gradle and Maven. Table of Contents What are the differences between jar and war? How to generate builts jar or war in spring boot? Deploying a JAR (Java Archive) as a standalone application Deploying a WAR (Web Application Archive) into a servlet container What are the differences between jar and war? jar (Java ARchive) war ( Web Application Resource) JAR stands for J ava AR chive. WAR   stands for W eb A pplication R esource, also stated W eb application AR chive. It is used to aggregate many Java class files and associated metadata and reso...

How to configure SSL certificate in spring boot?

Let us learn how to generate & configure the ssl certificates in spring boot applications. Step 1. Getting the certificate  We can purchase the SSL certificate from the following SSL providers   Godaddy DigiCert GeoTrust GlobalSign Comodo SSL RapidSSL SSL.com OR, for testing purposes, we can generate a self-signed certificate Before getting started, let us know the format of the SSL certificates: PKCS12:  Public Key Cryptographic Standards is a password-protected format that can contain multiple certificates and keys; it's an industry-wide used format. JKS:  Java KeyStore  is similar to PKCS12; it's a proprietary format and is limited to the Java environment. To know more about how SSL works please go to this link . We can use either keytool or OpenSSL tools to generate the certificates from the command line. Keytool  is shipped with Java Runtime Environment, and OpenSSL can be downloaded from  here . For our demonstratio...

Maven or Gradle - built tool selection in Spring Boot

  Spring Boot -Selection of built tool Gradle Gradle is an open-source build automation tool that is designed to be flexible enough to build almost any type of software, It is fully open source and similar to Maven and Ant. But Gradle has taken advantage of both Maven and Ant and also it has removed the disadvantages of Maven and Ant and created as a first-class built tool. It uses domain-specific language based on the programming language Groovy , differentiating it from Apache Maven, which uses XML for its project configuration. Gradle allows to create or customize built procedure and we can create an additional task with groovy scripts that can be executed before/after built. It also determines the order of tasks run by using a directed acyclic graph . Several developers created Gradle and first released in 2007, and in 2013, it was adopted by Google as the build system for Android projects. It was designed to support multi-project builds that are expected...