Monday, November 26, 2018

Spring Boot JDBC implementation

Spring Boot JDBC implementation - Hello World Example

In a previous post we had created an application using JDBC and seen the disadvantages. In another post we had seen the advantages of using Spring JDBC. In this chapter we see how to implement JDBC using Spring boot with MySql database.

Spring Boot JDBC Example

Why use Spring Boot JDBC-
The functionality of Spring JDBC and Spring Boot JDBC are the same. Only the implementation is made simple. The following are the advantages of Spring Boot JDBC over Spring JDBC.

JDBC using Spring Boot:
  • Only a single spring-boot starter dependency is required.
  • Datasource bean gets initialized automatically if not mentioned explicitly.
    If user does not want this then it can be done by setting the property spring.datasource.initialize to false.
  • If the Template beans PlatformTransactionManager, JdbcTemplate, NamedParameterJdbcTemplate not registered, then Spring Boot will register them automatically.
  • Any db initialization scripts stored in schema-.sql gets executed automatically.

Lets Begin-
The project will be as follows- 

Add the spring-jdbc-starter dependency.
<?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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.Example</groupId>
 <artifactId>boot-jdbc</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>boot-jdbc</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.2.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

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

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
 </dependencies>

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


</project>

In the application.properties file specify the datasource properties
spring.datasource.url=jdbc:mysql://localhost/cameldb
spring.datasource.username=root
spring.datasource.password=rida
spring.datasource.platform=mysql
Create the schema-mysql.sql file and specify the initialization scripts-
DROP TABLE IF EXISTS employee;

CREATE TABLE employee (
  empId VARCHAR(10) NOT NULL,
  empName VARCHAR(100) NOT NULL
);

Create the Employee Domain class
package com.Example.model;

public class Employee {

 private String empId;
 private String empName;

 public String getEmpId() {
  return empId;
 }

 public void setEmpId(String empId) {
  this.empId = empId;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

 @Override
 public String toString() {
  return "Employee [empId=" + empId + ", empName=" + empName + "]";
 }

}
Create Service interface to specify employee operations to be performed.
package com.Example.service;

import java.util.List;

import com.Example.model.Employee;

public interface EmployeeService {
 void insertEmployee(Employee emp);
 void insertEmployees(List<Employee> employees);
 void getAllEmployees();
 void getEmployeeById(String empid);
}

The Service class implementation.
package com.Example.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.Example.dao.EmployeeDao;
import com.Example.model.Employee;
import com.Example.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService {

 @Autowired
 EmployeeDao employeeDao;

 @Override
 public void insertEmployee(Employee employee) {
  employeeDao.insertEmployee(employee);
 }

 @Override
 public void insertEmployees(List<Employee> employees) {
  employeeDao.insertEmployees(employees);
 }

 public void getAllEmployees() {
  List<Employee> employees = employeeDao.getAllEmployees();
  for (Employee employee : employees) {
   System.out.println(employee.toString());
  }
 }

 @Override
 public void getEmployeeById(String empId) {
  Employee employee = employeeDao.getEmployeeById(empId);
  System.out.println(employee);
 }

}

Create the DAO interface.
package com.Example.dao;

import java.util.List;

import com.Example.model.Employee;

public interface EmployeeDao {
 void insertEmployee(Employee cus);
 void insertEmployees(List<Employee> employees);
 List<Employee> getAllEmployees();
 Employee getEmployeeById(String empId);
}
The DAO implementation class.
package com.Example.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.Example.dao.EmployeeDao;
import com.Example.model.Employee;

@Repository
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao{
 
 @Autowired 
 DataSource dataSource;
 
 @PostConstruct
 private void initialize(){
  setDataSource(dataSource);
 }
 
 @Override
 public void insertEmployee(Employee emp) {
  String sql = "INSERT INTO employee " +
    "(empId, empName) VALUES (?, ?)" ;
  getJdbcTemplate().update(sql, new Object[]{
    emp.getEmpId(), emp.getEmpName()
  });
 }
 
 @Override
 public void insertEmployees(List<Employee> employees) {
  String sql = "INSERT INTO employee " + "(empId, empName) VALUES (?, ?)";
  getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
   public void setValues(PreparedStatement ps, int i) throws SQLException {
    Employee employee = employees.get(i);
    ps.setString(1, employee.getEmpId());
    ps.setString(2, employee.getEmpName());
   }
   
   public int getBatchSize() {
    return employees.size();
   }
  });

 }
 @Override
 public List<Employee> getAllEmployees(){
  String sql = "SELECT * FROM employee";
  List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
  
  List<Employee> result = new ArrayList<Employee>();
  for(Map<String, Object> row:rows){
   Employee emp = new Employee();
   emp.setEmpId((String)row.get("empId"));
   emp.setEmpName((String)row.get("empName"));
   result.add(emp);
  }
  
  return result;
 }

 @Override
 public Employee getEmployeeById(String empId) {
  String sql = "SELECT * FROM employee WHERE empId = ?";
  return (Employee)getJdbcTemplate().queryForObject(sql, new Object[]{empId}, new RowMapper<Employee>(){
   @Override
   public Employee mapRow(ResultSet rs, int rwNumber) throws SQLException {
    Employee emp = new Employee();
    emp.setEmpId(rs.getString("empId"));
    emp.setEmpName(rs.getString("empName"));
    return emp;
   }
  });
 }
}
Finally create the class with @SpringBootApplication annotation.
package com.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import com.Example.model.Employee;
import com.Example.service.EmployeeService;
import com.Example.service.impl.EmployeeServiceImpl;

@SpringBootApplication
public class SpringBootJdbcApplication {
 
 
 @Autowired
 EmployeeService employeeService;

 public static void main(String[] args) {
  ApplicationContext context = SpringApplication.run(SpringBootJdbcApplication.class, args);
  EmployeeService employeeService = context.getBean(EmployeeService.class);
  
  
  Employee emp= new Employee();
  emp.setEmpId("emp");
  emp.setEmpName("emp");
  
  Employee emp1= new Employee();
  emp1.setEmpId("emp1");
  emp1.setEmpName("emp1");
  
  Employee emp2= new Employee();
  emp2.setEmpId("emp2");
  emp2.setEmpName("emp2");

  
  employeeService.insertEmployee(emp);

  List<Employee> employees = new ArrayList<>();
  employees.add(emp1);
  employees.add(emp2);
  employeeService.insertEmployees(employees);

  employeeService.getAllEmployees();
  
  employeeService.getEmployeeById(emp1.getEmpId());

 }
}
Start the application-

Spring Boot JDBCTemplate Example

Sunday, November 18, 2018

Spring Boot Tutorial-Spring Data JPA Simple Example

Spring Boot Tutorial-Spring Data JPA Simple Example

In this post we create a Employee management system which adds and retrieves employee details. 


Lets Begin
We make use of the h2 database. Maven will be as follows-
<?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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.EXP</groupId>
 <artifactId>SpringBootHelloWorld</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootHelloWorld</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.1.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <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>com.h2database</groupId>
   <artifactId>h2</artifactId>
  </dependency>

  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
  </dependency>

  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>

 </dependencies>

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


</project>
 
Create the SpringBootHelloWorldApplication.java as follows-
package com.EXP;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class SpringBootHelloWorldApplication {

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

Create the Entity class as follows-
package com.EXP.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Employee {
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Id
 private long id;

 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getDept() {
  return dept;
 }

 public void setDept(String dept) {
  this.dept = dept;
 }

 private String dept;

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", dept=" + dept + "]";
 }

}
 
The Controller we define methods to add Employee record and display employee records as list. Define the controller as follows-
package com.EXP.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.EXP.data.EmployeeRepository;
import com.EXP.model.Employee;

@Controller
public class EmployeeController {

 @Autowired
 private EmployeeRepository employeeData;

 @RequestMapping(value = "/addNewEmployee.html", method = RequestMethod.POST)
 public String newEmployee(Employee employee) {

  employeeData.save(employee);
  return ("redirect:/list.html");

 }

 @RequestMapping(value = "/addNewEmployee.html", method = RequestMethod.GET)
 public ModelAndView addNewEmployee() {

  Employee emp = new Employee();
  return new ModelAndView("newEmployee", "form", emp);

 }

 @RequestMapping(value = "/listEmployees.html", method = RequestMethod.GET)
 public ModelAndView employees() {
  List<Employee> allEmployees = employeeData.findAll();
  return new ModelAndView("allEmployees", "employees", allEmployees);

 }

}

Next we define the EmployeeRepository which is an interface that extends the Spring Framework class JpaRepository. JpaRepository class is a generics and takes the following two parameters as arguments-
  • What type of Object will this repository be working with- In our case Employee
  • Id will be what type of object- Long(since id defined in the Employee class is long)
Thats the only configuration required for the repository class. The required operations like adding and retrieving employee details from DB will now be handled. 
package com.EXP.data;

import org.springframework.data.jpa.repository.JpaRepository;

import com.EXP.model.Employee;

public interface EmployeeRepository extends JpaRepository<Employee
   , Long> {

}
Define the newEmployee.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h1>Employees page</h1>

<ul>
<c:forEach items="" var="employee">
   <li></li>
</c:forEach>
</ul>
 

Define the allEmployees.jsp
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <h1>Add new employee</h1>
        
    <form:form modelAttribute="form">
        <form:errors path="" element="div" />
        <div>
            <form:label path="name">Name</form:label>
            <form:input path="name" />
            <form:errors path="name" />
        </div>
        <div>
            <input type="submit" />
        </div>
    </form:form>
</body>
</html>
 

The application.properties will be as follows-
spring.mvc.view.prefix:/WEB-INF/jsp/
spring.mvc.view.suffix:.jsp

spring.datasource.url=jdbc:h2:file:./DB
spring.jpa.properties.hibernate.hbm2ddl.auto=update

Compile and the run the SpringBootHelloWorldApplication.java as a Java application.
Go to localhost:8080/addNewEmployee.html

Click add. We will be directed to the allEmployees.jsp



Sunday, November 11, 2018

Consuming RESTful Web Services / Servlet Filters


This chapter will discuss in detail about two different part of Spring Boot. First of them is consuming a RESTful Web Services by using jQuery AJAX and the other part is Servlet Filters.

1.Consuming RESTful Web Services

Create a simple Spring Boot web application and write a controller class files which is used to redirects into the HTML file to consumes the RESTful web services.
We need to add the Spring Boot starter Thymeleaf and Web dependency in our build configuration file.
Thymeleaf is a Java-based library used to create a web application. It provides a good support for serving a XHTML/HTML5 in web applications.
For Maven users, add the below dependencies in your pom.xml file.
<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>
The code for @Controller class file is given below −
@Controller
public class ViewController {
}
You can define the Request URI methods to redirects into the HTML file as shown below −
@RequestMapping(“/view-products”)
public String viewProducts() {
   return view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
   return add-products”;
}
This API http://localhost:9090/products should return the below JSON in response as shown below −
[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]
Now, create a view-products.html file under the templates directory in the classpath.
In the HTML file, we added the jQuery library and written the code to consume the RESTful web service on page load.
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
   $.getJSON("http://localhost:9090/products", function(result){
      $.each(result, function(key,value) {
         $("#productsJson").append(value.id+" "+value.name+" ");
      }); 
   });
});
</script>
The POST method and this URL http://localhost:9090/products should contains the below Request Body and Response body.
The code for Request body is given below −
{
   "id":"3",
   "name":"Ginger"
}
The code for Response body is given below −
Product is created successfully
Now, create the add-products.html file under the templates directory in the classpath.
In the HTML file, we added the jQuery library and written the code that submits the form to RESTful web service on clicking the button.
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function() {
         var productmodel = {
            id : "3",
            name : "Ginger"
         };
         var requestJSON = JSON.stringify(productmodel);
         $.ajax({
            type : "POST",
            url : "http://localhost:9090/products",
            headers : {
               "Content-Type" : "application/json"
            },
            data : requestJSON,
            success : function(data) {
               alert(data);
            },
            error : function(data) {
            }
         });
      });
   });
</script>
The complete code is given below.
Maven – 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 
   http://maven.apache.org/xsd/maven-4.0.0.xsd>
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath />
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

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

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>

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

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
   
</project>
The controller class file given below – ViewController.java is given below −

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

@Controller
public class ViewController {
   @RequestMapping(“/view-products”)
   public String viewProducts() {
      return view-products”;
   }
   @RequestMapping(“/add-products”)
   public String addProducts() {
      return add-products”;   
   }   
}
The view-products.html file is given below −
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>View Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
      <script>
         $(document).ready(function(){
            $.getJSON("http://localhost:9090/products", function(result){
               $.each(result, function(key,value) {
                  $("#productsJson").append(value.id+" "+value.name+" ");
               }); 
            });
         });
      </script>
   </head>
   
   <body>
      <div id = "productsJson"> </div>
   </body>
</html>
The add-products.html file is given below −
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1" />
      <title>Add Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
      <script>
         $(document).ready(function() {
            $("button").click(function() {
               var productmodel = {
                  id : "3",
                  name : "Ginger"
               };
               var requestJSON = JSON.stringify(productmodel);
               $.ajax({
                  type : "POST",
                  url : "http://localhost:9090/products",
                  headers : {
                     "Content-Type" : "application/json"
                  },
                  data : requestJSON,
                  success : function(data) {
                     alert(data);
                  },
                  error : function(data) {
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
      <button>Click here to submit the form</button>
   </body>
</html>
The main Spring Boot Application class file is given below −

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);
   }
}
Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven 
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
Run the JAR file by using the following command −
java –jar <JARFILE> 
Now, the application has started on the Tomcat port 8080.
Started Application on Tomcat Port_8080

Angular JS

To consume the APIs by using Angular JS, you can use the examples given below −
Use the following code to create the Angular JS Controller to consume the GET API - http://localhost:9090/products −
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.get('http://localhost:9090/products').
   then(function(response) {
      $scope.products = response.data;
   });
});
Use the following code to create the Angular JS Controller to consume the POST API - http://localhost:9090/products −
angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.post('http://localhost:9090/products',data).
   then(function(response) {
      console.log("Product created successfully");
   });
});
Note − The Post method data represents the Request body in JSON format to create a product.

2. Servlet Filters


A filter is an object used to intercept the HTTP requests and responses of your application. By using filter, we can perform two operations at two instances −
  • Before sending the request to the controller
  • Before sending a response to the client.
The following code shows the sample code for a Servlet Filter implementation class with @Component annotation.
@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter
      (ServletRequest request, ServletResponse response, FilterChain filterchain) 
      throws IOException, ServletException {}

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}
The following example shows the code for reading the remote host and remote address from the ServletRequest object before sending the request to the controller.
In doFilter() method, we have added the System.out.println statements to print the remote host and remote address.

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.stereotype.Component;

@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) 
      throws IOException, ServletException {
      
      System.out.println("Remote Host:"+request.getRemoteHost());
      System.out.println("Remote Address:"+request.getRemoteAddr());
      filterchain.doFilter(request, response);
   }

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}
In the Spring Boot main application class file, we have added the simple REST endpoint that returns the “Hello World” string.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String hello() {
      return "Hello World";
   }
}
The code for Maven build – pom.xml is given below −
<?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/xsd/maven-4.0.0.xsd">
   
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.8.RELEASE</version>
      <relativePath/> 
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</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>
You can create an executable JAR file, and run the Spring Boot application by using the Maven commands shown below −
mvn clean install
After BUILD SUCCESS, you can find the JAR file under the target directory.
Now, run the JAR file by using the following command
java –jar <JARFILE> 

Then, you can see the Remote host and Remote address on the console log as shown below −
Remote Host Remote Address on Console Log