SEARCH BY

All

  • All
  • Java8
  • Spring

Simple SpringBoot Application to retrieve data from data base

Post a Comment
Here iam trying to share a good notes on Spring Boot concepts which includes the following annotations
@Service
@SpringBootApplication
@RestController
@CrossOrigin
@RequestMapping
@ReqsponseBody
@PathParam
@RequestParam
@JsonProperty
@Autowired

Concept of Application:

Here we are trying to get the list of students details from database and displaying as web page view by using JQuery Ajax request to REST end point of Spring Boot Rest Controller.



Students list displayed with the url http://localhost:9090/jkl/students.html
The above screen is the final output of the  application we are discussing and developing in this article.

Now we will see the purpose of Annotations listed above in the starting of this article.

@Service: is the annotation using as a class annotation to make a class as Service, Spring Container understands a class which annotated with @Service is a service class which contains Business logic of the application or a component of the application.

@SpringBootApplication: this is the new annotation SpringBoot, this annotation is the combination of three annotations (@EnableAutoConfiguration, @ComponentScan, @Configuration ), if we annotated a class with @SpringBootApplication then that class is indirectly annotated with the three annotations (@Configuration,@EnableAutoConfiguration,@ComponentScan). Starting point of the SpringBoot application starts from the class which annotated with @SpringBootApplication.

@RestController: is the class which is creating a class which is an end point for REST requests. @RestComtroller is equivalent to the combination of @Controller and @ResponeBody which has request handler methods to service END point requests.

@CrossOrgin: is the powerful annotation when we want to allow our Spring Boot Rest End point to  access by third party site ( ie other than our spring boot application ). This @Annotation lets the application to over come the error Access-Control-Request-Method.
 @CrossOrigin(origins = "*", allowedHeaders = "*") this allows all origins(domains or ips) to access the end point.


@RequestMapping: This is the class level and method level annotation which is for creating end points by specifying request method like get,post,put etc...
@RestController
@RequestMapping(path="/engstu")
public class EngStudent{
// Body of Rest Controller with request handler methods

@RequestMapping(path="getAllStudents", method=RequestMethod.GET, produces="application/json")
public List getAllS(){
// body of handler method can be included here
}
}



@ResponseBody: This is the annotation which will bind an output of handler method as web response object(HTTP response object). This is a class level and method level annotation. If a class annotated with @RestController then automatically method is annotated with @Controller and @ResponseBody, so each and every request handler method is annotated with @ResponseBody automatically.

@PathParam: is annotation at method parameter level to get the value from SEO URL pattern like user request
@reqestMapping(path="/student/{stid}", method=RequestMethod.GET, produces="application/json")
public Student getStudentByID(@PathParam int stid){

}
@RequestParam: is an annotation at method parameter level to get the value from url which is with ? mark ( ....?lang=English ) here lang is the request parameter.

@JsonProperty: is the annotation at variable level for specifying new name for JSON key , which will be different than POJO class variable. for example
@JsonProperty(value="student-name")
String name;

in the above name is a variable working with in the code, but student-name is the json variable which will be reflected in the JSON output generated by REST end point.

@Autowired: is a powerful annotation in Spring Boot to inject bean at required place.

We are adding the following spring boot starters and dependencies into POM.xml file

web, jpa startes and h2 database dependency are adding into POM.xml file, groupID of application is com.jsite.html and artifactiD of application is eng-heroes where project/application name is demo-1 and you can see some other details in POM.xml file bello
<?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.5.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.jsite.html</groupId>
 <artifactId>eng-heroes</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>demo-1</name>
 <description>Demoproject for Micrsoservices</description>

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

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
 <!--   <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency> -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
  </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>
  <dependency>
   <groupId>org.springframework.security</groupId>
   <artifactId>spring-security-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>

First we are going to create a plain java class which is for Student information. Here following is the Student class


/**
 * 
 */
package com.jsite.heroes.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author JaiCeoSattvaQ
 *
 */
public class Student {
 
 
 @JsonProperty(value="hero-name")
 private String name;
 
 @JsonProperty(value="hero-id")
 private int id;
 
 @JsonProperty(value="hero-allegiance")
 private String allegeience;
 
 @JsonProperty(value="hero-title")
 private String title;
 
 @JsonProperty(value="hero-image-url")
 private String imgurl;
 
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getAllegeience() {
  return allegeience;
 }
 public void setAllegeience(String allegeience) {
  this.allegeience = allegeience;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getImgurl() {
  return imgurl;
 }
 public void setImgurl(String imgurl) {
  this.imgurl = imgurl;
 }
 
 
}



Now we will see Rest controller of this application which uses @RestController, @CrosOrigin, @RequestMapping, @PathVariable, @RequestParam, @Autowired annonations.
package com.jsite.heroes.controllers;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jsite.heroes.pojo.Student;
import com.jsite.heroes.services.StudentService;

/**
 * @author JaiCeoSattvaQ
 *
 */
@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping(path="/engstu")
public class EngStudents {

 @Autowired
 private StudentService ss;
 
 
 @RequestMapping(path="/getStudentsList", method=RequestMethod.GET, produces="application/json")
 public  List<Student> getStudents(){
  List<Student> listS= ss.getStudentsList();
  return listS;
 }
 
 @RequestMapping(path="/student/{id}", method=RequestMethod.GET)
 public  Student getStudentById(@PathVariable int id, @RequestParam String lang) {
  System.out.println("Student Id from Pathavariable"+id + "Language selected from RequestParam"+lang);
  return new Student();
 }

}


We are using RowMapper with JDBCTempalte to get Students details from Database
following is the service class which uses @Service, JDBCTempalte and RowMapper concept

/**
 * 
 */
package com.jsite.heroes.services;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.jsite.heroes.pojo.Student;
import com.jsite.heroes.rowmappers.student.StudentRowMapper_AllStudents;

/**
 * @author JaiCeoSattvaQ
 *
 */
@Service
public class StudentService {
 
@Autowired
JdbcTemplate jt;

public List<Student> getStudentsList(){
 
 String q="SELECT * FROM GOT_HEROES ";
 List<Student> listS= new ArrayList<Student>();
 RowMapper<Student> rowMapper= new StudentRowMapper_AllStudents();
 listS= jt.query(q, rowMapper);
 
 /*
 jt.query(q, resultSet -> {
  
  Student s= new Student();
  
  s.setId(resultSet.getInt("hero_id"));
  s.setName(resultSet.getString("hero_name"));
  s.setTitle(resultSet.getString("hero_title"));
  s.setImgurl(resultSet.getString("hero_image_url"));
  s.setAllegeience(resultSet.getString("hero_allegiance"));
  listS.add(s);
  }); */
return listS;
}
}


RowMapper implemented class to map retrieved values with a POJO class(Student.class in our application)
/**
 * 
 */
package com.jsite.heroes.rowmappers.student;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.jsite.heroes.pojo.Student;

/**
 * @author JaiCeoSattvaQ
 *
 */
public class StudentRowMapper_AllStudents implements RowMapper<Student> {

 @Override
 public Student mapRow(ResultSet resultSet, int rowNum) throws SQLException {
  // TODO Auto-generated method stub
  Student s= new Student();
  s.setId(resultSet.getInt("hero_id"));
  s.setName(resultSet.getString("hero_name"));
  s.setTitle(resultSet.getString("hero_title"));
  s.setImgurl(resultSet.getString("hero_image_url"));
  s.setAllegeience(resultSet.getString("hero_allegiance"));
  
  return s;
 }

}
here the following is the content of application.properties file which includes context path, tomcat port number details along with h2 database connection strings.
server.servlet.context-path=/jkl
server.port=${PORT:9090}


# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.h2.console.settings.web-allow-others=true
# Datasource
spring.datasource.url=jdbc:h2:file:~/GOT_DB;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=pk
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

Now we see the front end view page code for displaying Students information as a HTML table. create Students.html in static folder of resources folder of Spring Boot application, in the bellow code you can notice that line number 12 includes REST endpoint to get all students details.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GOT Heroes!</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  crossorigin="anonymous"></script>
    <script>
        $(document).ready(
            function(){
                $.get({
                    url: '/jkl/engstu/getStudentsList',
                    method: 'GET',
                    success: function(msg){
                        var innerHtml = '';
                        msg.forEach(function(each){
                            innerHtml = innerHtml +
                                '<tr><td align="center"><img width="40" height="70" src="'+each['hero-image-url']+'"/></td>' +
                                '<td>'+each['hero-name']+'</td>' +
                                '<td>'+each['hero-title']+'</td>' +
                                '<td>'+each['hero-allegiance']+'</td></tr>'
                        });
                        $("#hero-body").append(innerHtml);
                    }
                });
            }
        )

        var logout = function(){
            document.getElementById("logoutForm").submit();
            //window.location.href = "/heros.html";
        }

    </script>
</head>
<body>
<div class="container">
<div class="row">
    <div class="col-2">&nbsp;</div>
    <div class="col-8" align="center">
       <h1>Students List</h1>
    </div>
    <div class="col-2" align="right"><a href="#" onclick="javascript:logout()">logout</a></div>
</div>
</div>
<div class="row">
<div class="col-2">&nbsp;</div>
<div class="col-8">
    <table class="table">
        <thead>
            <tr>
                <th scope="col"></th>
                <th scope="col">Student Name</th>
                <th scope="col">Student Title</th>
                <th scope="col">Student House Allegiance</th>
            </tr>
        </thead>
        <tbody id="hero-body"></tbody>
    </table>
</div>
<div class="col-2">&nbsp;</div>
</div>
</div>

<form id="logoutForm" style="visibility:hidden" action="/jkl/logout" method="post"></form>
</body>
</html>

reference: https://medium.com/@prnmkmth/a-step-by-step-guide-to-a-spring-boot-microservices-workshop-for-wwcode-part-1-a5ff89a84016
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox