Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
52 views102 pages

9 Spring Boot

all about 9 Spring Boot

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views102 pages

9 Spring Boot

all about 9 Spring Boot

Uploaded by

rakeshmishrare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

www.jtcindia.

org 1 Spring Boot 2


1) Spring offers a powerful way to build web applications, with support for
dependency injection, transaction management, polyglot persistence, application
security, first-hand REST API support, an MVC framework and a lot more.

2) Spring applications have always required significant configuration and, which


sometimes build up a lot of complexity during development. That’s where Spring
Boot comes in.

3) The Spring Boot project aims to make building web application with Spring much
faster and easier. The guiding principle of Boot is convention over configuration.

Important features in Spring Boot:

1. Spring Boot Starters


2. Auto Configurations

3. Spring Boot Initializer

4. Spring Boot CLI


5. Dev Tools

6. Externalized Configurations

7. YAML Support

8. Embedded Containers
9. Actuators

10.Spring Boot Admin

www.jtcindia.org 2 Spring Boot 2


Lab1 : Working Steps:
A) Setup Database
create database myjtcdb;
use myjtcdb;
create table
mycustomers( cid int
primary key,
cname char(10),
email char(10),
phone long,
city char(10)
);

B) Create the maven Project.


1) Open the Eclipse required Workspace
2) Select New -> Maven Project.
3) Check the checkbox for create Simple Project(skip the Archetype selection) and Click
on Next Button.
4) Provide the following
Group Id: com.jtcindia.spring Artifact Id :
Lab1
Version : 1.0
packaging : jar
Name : MyLab1
and Click On finish button.

5) Add the maven-compiler-plugin


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
6) You can see the Error in Maven Project.
Fix the Error by updating the Maven Project.
Select the Project , right click and then select Maven -> Update Project.
www.jtcindia.org 3 Spring Boot 2
7) Update pom.xml by adding the following dependencies.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version5.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version5.2.5.RELEASE</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

8) Write JTCAppConfig.java ( Bean Configuration class)


 Configure DataSource.
 Configure JdbcTemplate

9) Write the following Files


 Customer.java
 CustomerRowMapper.java

10) Write the DAO and its Implementation class


 CustomerDAO.java
 CustomerDAOImpl.java

11) Write Client Program - Lab1 and Run it.

www.jtcindia.org 4 Spring Boot 2


Lab1: Files required

1. Lab1.java
2. CustomerDAO.java
3. CustomerDAOImpl.java
4. Customer.java
5. CustomerRowMapper.java
6. JTCAppConfig.java
7. pom.xml

1) Lab1.java
package com.jtcindia.spring;

import java.util.List;
import org.springframework.context.annotation.*;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public class Lab1 {

public static void main(String[] args) {

AnnotationConfigApplicationContext ctx=new
AnnotationConfigApplicationContext(JTCConfig.class);
CustomerDAO cdao=(CustomerDAO) ctx.getBean("custDAO");

// 1. addCustomer
Customer cust1 = new Customer(104, "SP", "SP@jtc", 9999, "Noida");
cdao.addCustomer(cust1);

// 2. getAllCustomers
System.out.println("getAllCustomers");
List<Customer> list=cdao.getAllCustomers();
list.forEach( cust -> System.out.println(cust) );
}
}

www.jtcindia.org 5 Spring Boot 2


2) CustomerDAO.java
package com.jtcindia.spring;

import java.util.List;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public interface CustomerDAO {
public void addCustomer(Customer cust);
public List<Customer> getAllCustomers();
}

3) CustomerDAOImpl.java
package com.jtcindia.spring;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@Repository("custDAO")
public class CustomerDAOImpl implements CustomerDAO {

@Autowired
JdbcTemplate jdbcTemp;

public void addCustomer(Customer cust) {


String sql = "insert into customers values(?,?,?,?,?)";
jdbcTemp.update(sql, cust.getCid(), cust.getCname(), cust.getEmail(), cust.getPhone(), cust.getCity());
}

public List<Customer> getAllCustomers()


{ String sql = "select * from customers";
List<Customer> list = jdbcTemp.query(sql, new CustomerRowMapper());
return list;
}

www.jtcindia.org 6 Spring Boot 2


4) Customer.java
package com.jtcindia.spring;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public class Customer
{ private int cid;
private String cname;
private String email;
private long phone;
private String city;

//Constructors
//Setters and Getters

public String toString() {


return "" + cid + "\t" + cname + "\t" + email + "\t" + phone + "\t"+ city;
}
}

5) CustomerRowMapper.java
package com.jtcindia.spring;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public class CustomerRowMapper implements RowMapper<Customer>
{ @Override
public Customer mapRow(ResultSet rs, int rn) throws SQLException
{ Customer cust=new Customer();
cust.setCid(rs.getInt(1));
cust.setCname(rs.getString(2));
cust.setEmail(rs.getString(3));
cust.setPhone(rs.getLong(4));
cust.setCity(rs.getString(5));
return cust;
}
}

www.jtcindia.org 7 Spring Boot 2


6) JTCAppConfig.java
package com.jtcindia.spring;

import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@Configuration
@ComponentScan(basePackages = {"com.jtcindia.spring"}) public
class JTCAppConfig {
@Bean
public DataSource dataSource() {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/myjtcdb");
bds.setUsername("root"); bds.setPassword("jtcsom");
bds.setInitialSize(10);
bds.setMaxActive(15);
return bds;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource ds)
{ return new JdbcTemplate(ds);
}
}
7) pom.xml
<project ……>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.spring</groupId>
<artifactId>Lab1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyLab1</name>
<url>http://maven.apache.org</url>
<properties>
<java.version>1.8</java.version>
<spring.version>5.1.9.RELEASE</spring.version>

www.jtcindia.org 8 Spring Boot 2


</properties>
<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

www.jtcindia.org 9 Spring Boot 2


Problems:
1) We need to update the pom.xml when ever I need some extra jars / replacing
Existing jars. (pom.xml)

2) Configuring Beans in Configuration class.(JTCAppConfig.java)

3) Hard-coding Configuration Data/Parameters (What happens when I change


the Configuration Data).

How SpringBoot Solves the Above Problems.


1) Starters.
 Gets All the Dependent Compatible Jars with given starter name.
 spring-boot-starter-jdbc
 spring-boot-starter-data-jpa
 spring-boot-starter-web

2) AutoConfiguration
 Most of the Beans will be configured by the Spring Container automatically.
 Beans will be configured conditionally based availability of Classes in the
Classpath.

3) Centralizing the Configuration Data


 You can centralize the Configuration Data/Parameters in Property Files or
YAML Files

Lab2 : Working Steps:


A) Setup Database
Same as Lab1

B) Create the maven Project.


1) Open the Eclipse required Workspace
2) Select New -> Maven Project.
3) Check the checkbox for create Simple Project(skip the Archetype selection) and Click
on Next Button.
4) Provide the following
Group Id: com.jtcindia.springboot
Artifact Id : Lab2
Version : 1.0
packaging : jar

www.jtcindia.org 10 Spring Boot 2


Name :MyLab2and
Click On finish button.

C) Start the Example Code.


1) Remove the following two Source Folders.
a. src/test/java
b. src/test/resources

2) Add the spring-boot-maven-plugin in pom.xml

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

3) Update pom.xml by adding the following dependencies.

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

<dependencies>

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

</dependencies>

4) You can see the Error in Maven Project.


Fix the Error by updating the Maven Project.
Select the Project , right click and then select Maven -> Update Project.

www.jtcindia.org 11 Spring Boot 2


5) Create application.properties under src/main/resources
6) Add the following properties in application.properties

#Database Properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root spring.datasource.password=jtcsom

#Hikari Properties
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

#Log Properties
logging.level.root=DEBUG
logging.pattern.console=%-5level %logger{36} - %msg%n

7) Write JTCAppConfig.java ( Bean Configuration class)


 No Beans to Configure

@Configuration
@ComponentScan(basePackages = {"com.jtcindia.springboot"})
public class JTCAppConfig {

8) Write the following Files (Copy from Lab1)


 Customer.java
 CustomerRowMapper.java

9) Write the DAO and its Implementation class (Copy from Lab1)
 CustomerDAO.java
 CustomerDAOImpl.java

10) Write Boot Main Class - MyBootApp and Run it.

Run As => Spring Boot Application

www.jtcindia.org 12 Spring Boot 2


Lab2: Files required

1. MyBootApp.java
2. CustomerDAO.java Same As Lab1
3. CustomerDAOImpl.java Same As Lab1
4. Customer.java Same As Lab1
5. CustomerRowMapper.java Same As Lab1
6. JTCAppConfig.java
7. application.properties
8. pom.xml

1) MyBootApp.java
package com.jtcindia.springboot;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@SpringBootApplication
public class MyBootApp implements CommandLineRunner {

@Autowired
CustomerDAO cdao;

public static void main(String[] args)


{ SpringApplication.run(MyBootApp.class, args);
}

@Override
public void run(String... args)
{ System.out.println("MyBootApp..run() method-- Starts");
System.out.println ("------------------------------------ ");

// 1. addCustomer
Customer cust1 = new Customer(98, "SP", "SP@jtc", 9999, "Noida");
cdao.addCustomer(cust1);

www.jtcindia.org 13 Spring Boot 2


// 2. getAllCustomers
System.out.println("getAllCustomers");
List<Customer> list=cdao.getAllCustomers();
list.forEach(cust -> System.out.println(cust) );

System.out.println ("------------------------------------ ");


System.out.println("MyBootApp..run() method-------Ends");
}
}

6) JTCAppConfig.java
package com.jtcindia.springboot;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */

@Configuration
@ComponentScan(basePackages = {"com.jtcindia.springboot"})
public class JTCAppConfig {

7) application.properties

#Database Properties
spring.datasource.url=jdbc:mysql://localhost:3306/jtcdb
spring.datasource.username=root spring.datasource.password=jtcsom

#Hikari Properties
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

#Log Properties
logging.level.root=DEBUG
logging.pattern.console=%-5level %logger{36} - %msg%n

www.jtcindia.org 14 Spring Boot 2


8) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>

<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab2</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>MyLab2</name>
<url>http://www.jtcindia.com</url>

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

<dependencies>

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

</dependencies>

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

www.jtcindia.org 15 Spring Boot 2


Q1) What are the Spring Boot features discussed till now?
Ans: 1. Spring Boot Starters
2. Auto Configuration
3. Centralizing Configuration Data with Property File /YAML

2) What is use of Spring Boot Starters?


Ans:
Each Starter brings some set of Jars and it’s Dependent and Compatible jars.

3) What is the Auto Configuration?


Ans:
Beans will be Configured by the Spring Boot automatically without explicit Configuration.
So Bean Instances will be available in Spring Container Readily.
You have to Inject those beans where ever you want.

4) Can I ask the Spring Boot to Auto-Configure CustomerDAOImpl?


Ans: No

5) Is it required to me to Configure CustomerDAOImpl in Bean Configuration class?


Ans: No

6) How to Configure the Beans which I am writing In My applications?


Ans:
A) Some Beans will be Instanciated with ComponentScan facility.
Your Application speciffic beans like Controllers,Business Services,DAO etc can be
marked with Steroype annotations called @Controller,@Service, @Repository .

B) Some Beans will be Auto-Configured by the Spring Boot.


All the Built-In Beans like JdbcTemplate, NamedParameterJdbcTemplate,
DataSourceTranactionManager
EntityManagerFactory, EntityManager,
JpaTranactionManager, JpaTemplate
DispatcherServlet, RabbitMqTemplate, KafkaTemplate

C) Some Beans has to be configured by You explicitly.


If above two cases are not possible then you have to configure the Bean explicitly.

www.jtcindia.org 16 Spring Boot 2


Q7) How Spring Boot will decide which bean to Auto-Configured?
Ans:
List of Beans will be Auto-Configured based on the Availability of Bean class in the Class Path.

 Already Some List of Beans are Prepared by Boot Team. (consider 100 Beans)
 At Boot Application Start-Up, Boot Scans All the Packages in the Classpath to Check whether
these Bean Classes are available in class path or not.
 Prepares CONDITIONS EVALUATION REPORT with Positive Matches and Negative Maches.
 You can see the CONDITIONS EVALUATION REPORT in debug mode.

Q8) What is the use of Property File / YAML File?


Ans : To Centalize the Bean Configuration Data.

Q9) Can I have both files (properties and yaml )?


Ans: Any one is enough, but you can write both.

Q10) I want to use custom jar in my Spring/Spring Boot application?


Ans:
 Push Your jar into Maven Local repo by specifying group Id and Artifact Id.
 Get that into your project by specifying the group Id and Artifact Id.

Q11) I want to Run My Labs in Oracle. What to do?


Ans: Using Maven Dependency , You can not get the Oracle Jar from Maven Global Repo.

 Download Oracle Jar file.


 Push Your jar into Maven Local repo by Specifing Group Id, Artifact Id,Version
 Specify the Maven Dependency in pom.xml with Above Specified Group Id, Artifact
Id,Version
 You can See Oracle Jar in your Project Dependencies.

Q12) What is the Default DataSource in Spring Boot 1.x?


Ans : TomcatCP

Q13) What is the Default DataSource in Spring Boot 2x?


Ans : HikariCP

Q14) Can I Change the Default DataSource to other Required DataSource?


Ans : Yes , You Can . (Refer Lab3 and Lab4)

www.jtcindia.org 17 Spring Boot 2


Q15) What happens when I provide Following 3 DataSources?
HikariCP TomcatCP DBCP2
Ans: HikariCP – Will be Selected (Refer Lab5)

Q16) What happens when I provide Following 2 DataSources?


DBCP2 TomcatCP
Ans: TomcatCP – Will be Selected

Q17) What happens when I am not providing Any DataSource after excluding Hikari?
Ans:

Lab3 : Working Steps:


1) Copy Lab2 and Paste as Lab3
2) Update the pom.xml
A) Exclude HikariCP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>

B) Add Dependency for Tomcat CP.


<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>

3) Update application.properties
A) Remove Hikari Properties
B) Add Tomcat Properties as follows
spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.max-active=25
4) Run the Application.
Run As => Spring Boot Application

www.jtcindia.org 18 Spring Boot 2


Lab3: Files required

1. MyBootApp.java Same As Lab2


2. CustomerDAO.java Same As Lab2
3. CustomerDAOImpl.java Same As Lab2
4. Customer.java Same As Lab2
5. CustomerRowMapper.java Same As Lab2
6. application.properties Updated
7. pom.xml Updated

6) application.properties

#Database Properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root
spring.datasource.password=SomPrakash

#Tomcat Properties
spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.max-active=25

#Log Properties
logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} - %msg%n

7) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>

<groupId>com.coursecube.springboot</groupId>
<artifactId>Lab3</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab3</name>
<url>http://www.jtcindia.org</url>

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

www.jtcindia.org 19 Spring Boot 2


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

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

www.jtcindia.org 20 Spring Boot 2


Lab4 : Working Steps:
1) Copy Lab2 and Paste as Lab4
2) Update the pom.xml
A) Exclude HikariCP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>

B) Add Dependency for DBCP2


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>

3) Update application.properties
C) Remove Tomcat Properties
D) Add DBCP2 Properties as follows

spring.datasource.dbcp2.initial-size=5
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true

4) Run the Application.


Run As => Spring Boot Application

www.jtcindia.org 21 Spring Boot 2


Lab4: Files required

1. MyBootApp.java Same As Lab2


2. CustomerDAO.java Same As Lab2
3. CustomerDAOImpl.java Same As Lab2
4. Customer.java Same As Lab2
5. CustomerRowMapper.java Same As Lab2
6. application.properties Updated
7. pom.xml Updated

6) application.properties

#Database Properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root
spring.datasource.password=SomPrakash

#DBCP2 Properties
spring.datasource.dbcp2.initial-size=5
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true

#Log Properties
logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} - %msg%n

7) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>
<groupId>com.coursecube.springboot</groupId>
<artifactId>Lab4</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab4</name>
<url>http://www.jtcindia.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>

www.jtcindia.org 22 Spring Boot 2


<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

</dependencies>

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

www.jtcindia.org 23 Spring Boot 2


Lab5 : Working Steps:
1) Copy Lab2 and Paste as Lab5
2) Update the pom.xml
A) Include HikariCP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

B) Add Dependency for DBCP2


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>

C) Add Dependency for Tomcat CP.


<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>

3) Update application.properties
A) Add HIkari Properties as follows

spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

B) Add Tomcat Properties as follows

spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.max-active=25

C) Add DBCP2 Properties as follows

spring.datasource.dbcp2.initial-size=5
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true

4) Run the Application.


Run As => Spring Boot Application

www.jtcindia.org 24 Spring Boot 2


Lab5: Files required

1. MyBootApp.java Same As Lab2


2. CustomerDAO.java Same As Lab2
3. CustomerDAOImpl.java Same As Lab2
4. Customer.java Same As Lab2
5. CustomerRowMapper.java Same As Lab2
6. application.properties Updated
7. pom.xml Updated

8) application.properties

#Database Properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root
spring.datasource.password=SomPrakash

#Hikari Properties
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

#Tomcat Properties
spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.max-active=25

#DBCP2 Properties
spring.datasource.dbcp2.initial-size=5
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true

#Log Properties
logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} - %msg%n

9) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>
<groupId>com.coursecube.springboot</groupId>
<artifactId>Lab5</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

www.jtcindia.org 25 Spring Boot 2


<name>Lab5</name>
<url>http://www.jtcindia.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>

<dependencies>

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

<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

</dependencies>

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

www.jtcindia.org 26 Spring Boot 2


Lab6: Files required

1. MyBootApp.java Updated in Lab6


2. CustomerDAO.java Updated in Lab6
3. CustomerDAOImpl.java Updated in Lab6
4. Customer.java Same As Lab2
5. CustomerRowMapper.java Same As Lab2
6. application.properties Updated in Lab6
7. application.yml New in Lab6
8. pom.xml Updated in Lab6

1) MyBootApp.java
package com.jtcindia.springboot;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@SpringBootApplication
public class MyBootApp implements CommandLineRunner{
static final Logger log = LoggerFactory.getLogger(MyBootApp.class);
@Autowired
CustomerDAO cdao;

public static void


main( String[]args ){ log.info("My Boot
App - Main() begin"); log.debug("My Boot
App - Main() begin");

SpringApplication.run(MyBootApp.class, args);

log.info("My Boot App - Main() end ");


log.debug("My Boot App - Main() end");
}

www.jtcindia.org 27 Spring Boot 2


public void run(String... args) throws Exception
{ log.info("My Boot App - run() begin");
log.debug("My Boot App - run() begin");
log.info("------------------------------------- ");

//Customer cust1=new Customer(501,"som","som@jtc",12345,"Noida");


//cdao.addCustomer(cust1);

List<Customer> list1=cdao.getAllCustomers();
list1.forEach(cust -> System.out.println(cust));

List<Customer> list2=cdao.getCustomersByCity("Noida");
list2.forEach(cust -> System.out.println(cust));

log.info("------------------------------------- ");
log.info("My Boot App - run() END");
log.debug("My Boot App - run() END");
}
}

2) CustomerDAO.java
package com.jtcindia.springboot;

import java.util.List;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public interface CustomerDAO {
public void addCustomer(Customer cust);
public List<Customer> getAllCustomers();
public List<Customer> getCustomersByCity(String city);
}

3) CustomerDAOImpl.java
package com.jtcindia.springboot;

import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA

www.jtcindia.org 28 Spring Boot 2


* */
@Repository("custDAO")
public class CustomerDAOImpl implements CustomerDAO{

@Autowired
NamedParameterJdbcTemplate npjdbcTemp;

@Override
public void addCustomer(Customer cust) {
String sql = "insert into mycustomers
values(:mycid,:mycname,:myemail,:myphone,:mycity)";
Map<String, Object> params = new HashMap<>();
params.put("mycid", cust.getCid());
params.put("mycname", cust.getCname());
params.put("myemail", cust.getEmail());
params.put("myphone", cust.getPhone());
params.put("mycity", cust.getCity());
npjdbcTemp.update(sql, params);
}

@Override
public List<Customer> getAllCustomers()
{ String SQL="select * from mycustomers";
List<Customer> list= npjdbcTemp.query(SQL,new CustomerRowMapper());
return list;
}

@Override
public List<Customer> getCustomersByCity(String city) {
String SQL="select * from mycustomers where city=:mycity";

Map<String, Object> params = new HashMap<>();


params.put("mycity", city);

List<Customer> list= npjdbcTemp.query(SQL,params, new


CustomerRowMapper());
return list;
}
}

www.jtcindia.org 29 Spring Boot 2


6) application.properties

#DataSource properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root
spring.datasource.password=jtcsom

#Hikari Properties
spring.datasource.hikari.connectionTimeout=10000
spring.datasource.hikari.maximumPoolSize=50

#Logging Properties
logging.level.com.zaxxer.hikari=DEBUG
logging.level.org.hibernate=INFO
logging.level.org.springframework=INFO
logging.level.com.jtcindia=DEBUG

logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} --- %msg %n

7) application.yml

spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/myjtcdb3
username: root
password: jtcsom
hikari.connectionTimeout: 10000
hikari.maximumPoolSize: 50

logging:
level:
root: INFO
com.zaxxer.hikari: DEBUG
org.hibernate: INFO
org.springframework: INFO
com.jtcindia: DEBUG

www.jtcindia.org 30 Spring Boot 2


8) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>

<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab6</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>MyLab6</name>
<url>http://www.jtcindia.org</url>

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

<dependencies>

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

</dependencies>

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

www.jtcindia.org 31 Spring Boot 2


Q18) What types of Parameters can be used when we write the Queries?
Ans:
Parameters are of Two Types:
1) Positional Parameters.
2) Named Parameters.

Q19) When Can I Use JdbcTemplate?


Ans:
When you want to use Positional Parameters.

Q20) When Can I Use NamedParameterJdbcTemplate?


Ans:
When you want to use Named Parameters.

Q21)Who manages the Version of MySQL when I am not Specifying the MySQL
Version?
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

Ans: Version is managed by Spring Boot based on the Spring boot Parent Version.

Defaults are as follows:


For Spring Boot 2.X => MySQL 8.x
For Spring Boot 1.5.x => MySQL 5.x

Q22) Can I use MySQL5 with Spring Boot? If so how it is?


Ans: Yes, You can specify the MySQL Version required explicitly.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.15</version>
</dependency>

www.jtcindia.org 32 Spring Boot 2


Q23) What are the Log Levels /Priorities Available?
Ans:
DEBUG, INFO, WARN, ERROR, FATAL

Q24) Is logger creates any performance issue in PROD Environment?


Ans:
Dev Mode : Use Debug
PROD Mode : INFO/WARN

Q25) What happens when I set INFO level for com?


Ans: logging.level.com=INFO
Log Level for All the packages Starts with com will be set to INFO.

Q26) How to use YAML Files (Yet Another Markup Language)?


Ans:
Create the file called application.yml under src/main/resources

Q27) How Spring Boot scans for application.properties or application.yml?


Ans: Spring Boot scans for these files in the Class path Resources. If found in the
classpath , You can the following in Logs.
Origin: class path resource [application.yml] Origin:
class path resource [application.properties]

Q28) What are the Annotations replaced by @ SpringBootApplication?


Ans:
Mark this Configuration class with @SpringBootApplication
which replacement of the following 3 annotations .
 @Configuration
 @ComponentScan(basePackages = "com.jtcindia.springboot")
 @EnableAutoConfiguration

Q29) What is the CommandLineRunner interface?


Ans:

Q30) What happens internally when you run the Spring Boot Application?
Ans:

www.jtcindia.org 33 Spring Boot 2


Lab7: Files required

1. MyBootApp.java 2. JTCAppConfig.java
3. Hello.java 4. Hai.java
5. HelloService.java 6. HelloDAO.java
7. application.properties 8. pom.xml

1) MyBootApp.java
package com.jtcindia.springboot;

import java.sql.*;
import javax.sql.DataSource;

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

import com.jtcindia.dao.HelloDAO; import


com.jtcindia.service.HelloService;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@SpringBootApplication(scanBasePackages = {"com.jtcindia"}) public
class MyBootApp implements CommandLineRunner{

@Autowired
Hello hello;

@Autowired
Hai hai;

@Autowired
HelloService helloService;

@Autowired
HelloDAO helloDAO;

@Autowired
DataSource myds;

www.jtcindia.org 34 Spring Boot 2


public static void main( String[]myargs )
{System.out.println("My Boot App - Main() begin");
SpringApplication.run(MyBootApp.class, myargs);
System.out.println("My Boot App - Main() end ");
}
public void run(String... args) throws Exception {
//Do Your Start-Up Tasks Here
System.out.println("I am run() CLR - doing Start-Up Tasks");
System.out.println("CLR - run() - Begin");

hello.show();
hai.show();
helloService.show();
helloDAO.show();

Connection con=myds.getConnection();
DatabaseMetaData dbmd=con.getMetaData();
System.out.println(dbmd.getDatabaseProductName());

System.out.println("CLR - run() - End");


}
@Bean
public Hello getHello()
{ return new Hello();
}
}

2) JTCAppConfig.java
package com.jtcindia.springboot;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@SpringBootApplication
public class JTCAppConfig {

@Bean
public Hai getHai() {
return new Hai();
}
}

www.jtcindia.org 35 Spring Boot 2


3) Hello.java
package com.jtcindia.springboot;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public class Hello {
public Hello() {
System.out.println("Hello-D.C");
}
public void show() {
System.out.println("Hello-show()");
}
}

4) Hai.java
package com.jtcindia.springboot;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
public class Hai {
public Hai() {
System.out.println("Hai-D.C");
}
public void show() {
System.out.println("Hai-show()");
}
}

5) HelloService.java
package com.jtcindia.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService
{ public HelloService() {
System.out.println("HelloService - D.C");
}
public void show() {
System.out.println("HelloService - show()");
}
}

www.jtcindia.org 36 Spring Boot 2


6) HelloDAO.java
package com.jtcindia.dao;
import org.springframework.stereotype.Repository;
/*
* @Author : Som Prakash Rai
* @company : JTCINDIA
* */
@Repository
public class HelloDAO {
public HelloDAO() {
System.out.println("HelloDAO - D.C");
}
public void show() {
System.out.println("HelloDAO - show()");
}
}

6) application.properties
#DataSource properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb3
spring.datasource.username=root
spring.datasource.password=jtcsom

#Logging Properties
logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} --- %msg %n

7) pom.xml
<project …..>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab7</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>MyLab7</name>
<url>www.jtcindia.org</url>

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

www.jtcindia.org 37 Spring Boot 2


<dependencies>

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

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

</dependencies>

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

Q29) What is the CommandLineRunner interface?


Ans:
1) Implement CommandLineRunner
2) Override run() method public void run(String... args) throws Exception {
3) write Code to perform some tasks at Boot Application Startup:
 Increase JVM Memory
 Load the cache data
 Check DB Connections
 Insert Some Data into DB
 Cross Check Third Party Apps Status etc

www.jtcindia.org 38 Spring Boot 2


Q30) What Happens Internally When you run the Boot Application?
Ans:

Q31) Who is responsible for Launching Spring Boot Application? Ans:


SpringApplication.run(MyBootApp.class, args);

Parameters of run() method


1) MyBootApp.class => Boot Main class
2) Command Line Args which are coming to main() method.

Q32) What are the Stereo Type Annotations?


Ans:
@Service
@Controller
@Repository
@Component

www.jtcindia.org 39 Spring Boot 2


Spring Boot–Hibernate Example
Lab8: Files required

1. MyBootApp.java 2. Customer.java
3. CustomerDAO.java 4. CustomerDAOImpl.java
5. JTCAppConfig.java 6. application.properties
7. pom.xml

1) MyBootApp.java
package com.JTCINDIA.springboot;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class MyBootApp implements CommandLineRunner{

static final Logger log = LoggerFactory.getLogger(MyBootApp.class);

@Autowired
CustomerDAO cdao;

public static void main( String[] args )


{ SpringApplication.run(MyBootApp.class, args);
}

public void run(String... args) throws Exception {


log.info("My Boot App - run() begin");
log.info(" ------------------------------------- ");
Customer cust1=new Customer("som","som@jtc",12345,"Noida");
cdao.addCustomer(cust1);

List<Customer> list1=cdao.getAllCustomers();
list1.forEach(cust -> System.out.println(cust));

www.jtcindia.org 40 Spring Boot 2


List<Customer>
list2=cdao.getCustomersByCity("Noida");
list2.forEach(cust -> System.out.println(cust));

log.info(" ------------------------------------- ");


log.info("My Boot App - run() END");
}
}

2) Customer.java
package com.JTCINDIA.springboot;

import javax.persistence.*;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Entity
@Table(name="mycustomers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="cid")
private int cid;

@Column(name="cname")
private String cname;

@Column(name="email")
private String email;

@Column(name="phone")
private long phone;

@Column(name="city")
private String city;

//Constructors
//Setters and Getters

@Override
public String to String() {
return cid + "\t" + name + "\t" + email + "\t" + phone + "\t" + city ;
}

www.jtcindia.org 41 Spring Boot 2


www.jtcindia.org 42 Spring Boot 2
3) CustomerDAO.java
package com.JTCINDIA.springboot;

import java.util.List;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
public interface CustomerDAO {
public void addCustomer(Customer cust);
public List<Customer> getAllCustomers();
public List<Customer> getCustomersByCity(String city);
}

4) CustomerDAOImpl.java
package com.JTCINDIA.springboot;

import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Repository("custDAO")
@Transactional
public class CustomerDAOImpl implements CustomerDAO{

@Autowired
HibernateTemplate htemp;

@Override
public void addCustomer(Customer cust) {
htemp.save(cust);
}

www.jtcindia.org 43 Spring Boot 2


@Override
public List<Customer> getAllCustomers() {
List<Customer> list= htemp.loadAll(Customer.class);
return list;
}
@Override
public List<Customer> getCustomersByCity(String city) {
DetachedCriteria dc=DetachedCriteria.forClass(Customer.class);
dc.add(Restrictions.eq("city", city));
List<Customer> list= (List<Customer> )htemp.findByCriteria(dc);
return list;
}
}

5) JTCAppConfig.java
package com.JTCINDIA.springboot;

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate5.*;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class JTCAppConfig {

@Bean(name="jtcSessionFactory")
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean factory=new LocalSessionFactoryBean();

Properties props=new Properties();


props.put("hibernate.show_SQL","true");
props.put("hibernate.hbm2ddl.auto","update");

factory.setHibernateProperties(props); //1
factory.setDataSource(dataSource); //2
factory.setPackagesToScan("com.JTCINDIA.springboot"); //3
return factory;
}

www.jtcindia.org 44 Spring Boot 2


@Bean(name="jtcHibernateTemplate")
public HibernateTemplate hibernateTemplate(SessionFactory sessionFactory) {
return new HibernateTemplate(sessionFactory);
}

@Bean(name="jtcHibernateTransactionManager")
public HibernateTransactionManager hibernateTransactionManager(SessionFactory
sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
}

6) application.properties
#DataSource properties
spring.datasource.url=jdbc:mysql://localhost:3306/myjtcdb
spring.datasource.username=root
spring.datasource.password=SomPrakash

#Hikari Properties
spring.datasource.hikari.connectionTimeout=10000
spring.datasource.hikari.maximumPoolSize=50

logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} --- %msg %n

7) pom.xml
<groupId>com.JTCINDIA.springboot</groupId>
<artifactId>Lab8</artifactId>
<version>1.0</version>

<packaging>jar</packaging>

<name>MyLab8</name>
<url>http://www.jtcindia.org</url>

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

www.jtcindia.org 45 Spring Boot 2


<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

</dependencies>

<build>
<plugins>

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

</plugins>
</build>

www.jtcindia.org 46 Spring Boot 2


Spring Boot–JPA Example

Lab9: Files required

1. MyBootApp.java Same as Lab8


2. Customer.java Same as Lab8
3. CustomerDAO.java Same as Lab8
4. CustomerDAOImpl.java Updated in Lab9
5. JTCAppConfig.java Updated in Lab9
6. application.properties Same as Lab8
7. pom.xml Same as Lab8

4) CustomerDAOImpl.java
package com.JTCINDIA.springboot;

import java.util.List;
import javax.persistence.*;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Repository("custDAO")
@Transactional
public class CustomerDAOImpl implements CustomerDAO{

@PersistenceContext
EntityManager entityManager;

@Override
public void addCustomer(Customer cust) {
entityManager.persist(cust);
}
@Override
public List<Customer> getAllCustomers() {
String JPAQL="from Customer cust";
List<Customer> list=
entityManager.createQuery(JPAQL,Customer.class)
.getResultList();
return list;
}

www.jtcindia.org 47 Spring Boot 2


@Override
public List<Customer> getCustomersByCity(String city) {
String JPAQL="from Customer cust where cust.city=?1";
List<Customer> list=
entityManager.createQuery(JPAQL,Customer.class)
.setParameter(1, city)
.getResultList();
return list;
}

5) JTCAppConfig.java
package com.JTCINDIA.springboot;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class JTCAppConfig {

@Bean(name="jpaVendorAdapter")
public JpaVendorAdapter getJpaVendor() {

HibernateJpaVendorAdapter jpaVendor=new HibernateJpaVendorAdapter();


jpaVendor.setDatabase(Database.MYSQL);
jpaVendor.setShowSql(true);
jpaVendor.setGenerateDdl(true);
jpaVendor.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");

return jpaVendor;
}

www.jtcindia.org 48 Spring Boot 2


@Bean(name="jtcEntityFactory")
public LocalContainerEntityManagerFactoryBean entityFactory(DataSource
dataSource,JpaVendorAdapter adaptor) {

LocalContainerEntityManagerFactoryBean factory=new
LocalContainerEntityManagerFactoryBean();

factory.setDataSource(dataSource); //1
factory.setJpaVendorAdapter(adaptor);//2
factory.setPackagesToScan("com.JTCINDIA.springboot"); //3

return factory;
}

@Bean(name="jtcJpaTransactionManager")
public JpaTransactionManager JpaTransactionManager(EntityManagerFactory Factory) {
return new JpaTransactionManager(Factory);
}
}

Spring Boot–JPA Example

Lab10: Files required

1. MyBootApp.java Same as Lab9


2. Customer.java Same as Lab9
3. CustomerDAO.java Same as Lab9
4. CustomerDAOImpl.java Same as Lab9
5. application.properties Same as Lab9
6. pom.xml Same as Lab9

▪ We can use JPA with Spring Boot without configure EntityManagerFactory and
JpaTransactionManager in Lab10 because these are Auto-Configured by Spring
Boot.

www.jtcindia.org 49 Spring Boot 2


Questions
Q33) What are the Bean Dependencies required for SessionFactory?
Ans:

Q34) What are the Bean Dependencies required for HibernateTemplate?


Ans:

Q35) What are the Bean Dependencies required for HibernateTransactionManager?


Ans:

Q36) What are the Bean Dependencies required for EntityManagerFactory?


Ans:

Q37) What are the Bean Dependencies required for JpaTransactionManager?


Ans:

Q38) Is it required to configure EntityManagerFactory and JpaTransactionManager for using


JPA with Spring Boot as done in Lab9?
Ans:
▪ No Need to Configure EntityManagerFactory and JpaTransactionManager.
▪ These two will be auto-configured by Spring Boot. Just Shown to know how to
Configure these two.
▪ Refer Lab10. We are able to run JPA with Spring without configure
EntityManagerFactory and JpaTransactionManager in Lab10.

Q39) What is the use of JpaVendorAdapter and What are the various JpaVendorAdapters
available?
Ans:
▪ JpaVendorAdapter is used to specify the JPA provider
▪ Interface JpaVendorAdapter.
▪ SPI interface that allows to plug in vendor-specific behavior into Spring's
EntityManagerFactory creators.
▪ Serves as single configuration point for all vendor-specific properties.
▪ JpaVendorAdapter implementation classes are
1. HibernateJpaVendorAdapter
2. EclipseLinkJpaVendorAdapter

www.jtcindia.org 50 Spring Boot 2


Q40) What are the Beans which are AutoConfigured by Spring Boot from the following?
Ans:
You Can Cross check which of the following beans will be AutoConfigured by Spring Boot
by Injecting as follows.
@Autowired(required = false) AutoConfigured

DataSource ds;

@Autowired(required = false) AutoConfigured

JdbcTemplate jtemp;

@Autowired(required = false) AutoConfigured

NamedParameterJdbcTemplate njtemp;

@Autowired(required = false) AutoConfigured

EntityManagerFactory emf;

@Autowired(required = false) AutoConfigured

JpaTranactionManager txManager;

@Autowired(required = false) No

SessionFactory sf;

@Autowired(required = false) No

HibernateTemplate htemp;

@Autowired(required = false) No

HibernateTransactionManager txManager;

www.jtcindia.org 51 Spring Boot 2


Spring JPA
EntityManager IMP Methods

1. void persist(Object entity)

2. <T> T merge(T entity)

3. void remove(Object entity)

4. <T> T getReference(Class<T> entityClass, Object primaryKey)

5. <T> T find(Class<T> entityClass, Object PK)

6. <T> T find(Class<T> entityClass, Object PK, LockModeType lockMode)

7. Query createQuery(String qlStr)

8. <T> TypedQuery<T>createQuery(String qlStr, Class<T> resultClass)

9. Query createNamedQuery(String name)

10. <T> TypedQuery<T> createNamedQuery(String nm, Class<T> resCls)

11. Query createNativeQuery(String qlStr)

12. Query createNativeQuery(String qlStr, Class resultClass)

13. <T> TypedQuery<T>createQuery(CriteriaQuery<T> criteriaQuery)

14. void refresh(Object entity)

15. Boolean contains(Object entity)

16. EntityTransaction getTransaction()

17. void detach(Object entity)

18. void clear()

19. void flush()

20. void close()

www.jtcindia.org 52 Spring Boot 2


Spring Boot–JPA Complete Example
Lab11: Files required

1. MyBootApp.java Updated in Lab10


2. Customer.java Same as Lab10
3. CustomerDAO.java Updated in Lab10
4. CustomerDAOImpl.java Updated in Lab10
5. application.properties Same as Lab10
6. pom.xml Same as Lab10
1. MyBootApp.java
package com.JTCINDIA.springboot;

import java.math.BigInteger;
import java.util.List;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication(scanBasePackages="com.JTCINDIA.springboot")
public class MyBootApp implements CommandLineRunner {

Logger log = LoggerFactory.getLogger(MyBootApp.class);

@Autowired
CustomerDAO cdao;

public static void main(String[] args) {


SpringApplication.run(MyBootApp.class, args);
}
@Override
public void run(String... args) {
log.info("My Boot Application...Starts - Lab8");
log.info(" ----------------------------------- ");

// 1. addCustomer
Customer cust1 = new Customer("som", "som@jtc", 1234,
"Noida"); cdao.addCustomer(cust1);

www.jtcindia.org 53 Spring Boot 2


// 2. updateCustomer
Customer cust2 = new Customer(1, "Som", "som@jtc", 8888, "Noida");
cdao.updateCustomer(cust2);

// 3. deleteCustomer
cdao.deleteCustomer(8);

// 4. getCustomerByCid
Customer cust3 = cdao.getCustomerByCid(55);
System.out.println(cust3);

//5.getAllCustomers
List<Customer> list=cdao.getAllCustomers();
list.forEach(cust -> System.out.println(cust));

//6.getCustomersByCity
list=cdao.getCustomersByCity("Noida");
list.forEach(cust -> System.out.println(cust));

//7.getCustomersByEmail
list=cdao.getCustomersByEmail("Sp@jtc");
list.forEach(cust -> System.out.println(cust));

//8.getCustomersByEmailAndPhone
list=cdao.getCustomersByEmailAndPhone("som@jtc",12345);
list.forEach(cust -> System.out.println(cust));

//9.getCustomersByEmailOrPhone
list=cdao.getCustomersByEmailOrPhone("som@jtc",9999);
list.forEach(cust -> System.out.println(cust));

//10.getCustomerCount
BigInteger big = cdao.getCustomerCount();
System.out.println("All Count : " + big.intValue());

//11.getCustomerCountByCity
big = cdao.getCustomerCountByCity("Noida");
System.out.println(" Count : " + big.intValue());

//12.getCityByEmail
String city = cdao.getCityByEmail("Som@jtc");
System.out.println(city);

www.jtcindia.org 54 Spring Boot 2


//13.getPhoneByEmail
long phone = cdao.getPhoneByEmail("Som@jtc");
System.out.println(phone);

//14.getCidByPhone
int cid = cdao.getCidByPhone(123);
System.out.println(cid);

log.info(" ----------------------------------- ");


log.info("My Boot Application...Ends - Lab8");
}
}
3. CustomerDAO.java
package com.JTCINDIA.springboot;

import java.math.BigInteger;
import java.util.List;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
public interface CustomerDAO {
public void addCustomer(Customer cust);
public void updateCustomer(Customer cust);
public void deleteCustomer(int cid);
public Customer getCustomerByCid(int cid);

public List<Customer> getAllCustomers();


public List<Customer> getCustomersByCity(String city);
public List<Customer> getCustomersByEmail(String email);
public List<Customer> getCustomersByEmailAndPhone(String email,long phone);
public List<Customer> getCustomersByEmailOrPhone(String email,long phone);

public BigInteger getCustomerCount();


public BigInteger getCustomerCountByCity(String city);
public String getCityByEmail(String email);
public long getPhoneByEmail(String email);
public int getCidByPhone(long phone);
}

www.jtcindia.org 55 Spring Boot 2


4. CustomerDAOImpl.java
package com.JTCINDIA.springboot;

import java.math.BigInteger;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */

@Repository
@Transactional
public class CustomerDAOImpl implements CustomerDAO {

@PersistenceContext
EntityManager entityManager;

public void addCustomer(Customer cust) {


entityManager.persist(cust);
}

public void updateCustomer(Customer cust) {


entityManager.merge(cust);
}

public void deleteCustomer(int cid) {


Customer cust=entityManager.getReference(Customer.class, cid);
entityManager.remove(cust);
}

public Customer getCustomerByCid(int cid) {


//Customer cust=entityManager.getReference(Customer.class, cid);
// System.out.println(cust);
// return cust;
return entityManager.find(Customer.class, cid);
}

www.jtcindia.org 56 Spring Boot 2


public List<Customer> getAllCustomers() {
String jpaql = "from Customer cust";
return entityManager.createQuery(jpaql, Customer.class).getResultList();
}

public List<Customer> getCustomersByCity(String city) {

String jpaql = "from Customer cust where city=?1";


return entityManager.createQuery(jpaql, Customer.class)
.setParameter(1, city)
.getResultList();
}

public List<Customer> getCustomersByEmail(String email) {

String sql="select * from customers where email=?";


return entityManager.createNativeQuery(sql, Customer.class)
.setParameter(1, email)
.getResultList();
}

public List<Customer> getCustomersByEmailAndPhone(String email,long phone) {

String jpaql = "from Customer cust where email=?1 and phone=?2";


return entityManager.createQuery(jpaql, Customer.class)
.setParameter(1, email)
.setParameter(2, phone)
.getResultList();
}

public List<Customer> getCustomersByEmailOrPhone(String email,long phone) {

String jpaql = "select * from customer where email=1 or phone=2";


return entityManager.createQuery(jpaql, Customer.class)
.setParameter(1, email)
.setParameter(2, phone)
.getResultList();
}

public BigInteger getCustomerCount() {

String sql="select count(*) from customers";


return (BigInteger) entityManager.createNativeQuery(sql).getSingleResult();
}

www.jtcindia.org 57 Spring Boot 2


public BigInteger getCustomerCountByCity(String city) {

String sql="select count(*) from customers where city=?";


return (BigInteger) entityManager.createNativeQuery(sql)
.setParameter(1,city)
.getSingleResult();
}

public String getCityByEmail(String email) {

String sql="select city from customers where email=?";


return (String)entityManager.createNativeQuery(sql)
.setParameter(1,email)
.getSingleResult();
}

public long getPhoneByEmail(String email) {

String sql="select phone from customers where email=?";


String str= (String) entityManager.createNativeQuery(sql)
.setParameter(1,email)
.getSingleResult();
return Long.parseLong(str);
}

public int getCidByPhone(long phone) {

String sql="select cid from customers where phone=?";


return (Integer)entityManager .createNativeQuery(sql)
.setParameter(1,phone)
.getSingleResult();

}
}

www.jtcindia.org 58 Spring Boot 2


 You can develop Spring MVC application with Spring Boot in two ways.
1. Develop as FAT JAR file.
2. Develop as WAR file
 FAT Jar is self executable application which contains Application Code +
Embedded Container
 You can execute the FAT jar as follows.
Java –jar HelloApp.jar
 WAR file is deployable application which can be deployed in any External
Container to run.

Lab16: Spring MVC with Boot (with JSP)


Working Steps:
A) Setup the Project
1) Create the maven Project.
a) Open the Eclipse required Workspace
b) Select New -> Maven Project.
c) Check the checkbox for create Simple Project(skip the Archetype selection) and
Click on Next Button.
d) Provide the following
Group Id: com.jtcindia.springboot Artifact Id :
Lab16
Version : 1.0
packaging : jar
Name : MyLab16and Click On finish button.

2) Remove the following two Source Folders.


a. src/test/java
b. src/test/resources

3) Create application.properties under src/main/resources

4) Update application.properties as follows


server.port=12345

5) Create the Source Folder called src/main/webapp


6) Create the Folder called WEB-INF under src/main/webapp
7) Create the Folder called myjsps under WEB-INF

www.jtcindia.org 91 Spring Boot 2


8) Update pom.xml by adding the following dependencies.

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

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

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

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

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

9) You can see the Error in Maven Project.


Fix the Error by updating the Maven Project.
Select the Project , right click and then select Maven -> Update Project.

10) Create the Package called com.jtcindia.springboot under src/main/java

www.jtcindia.org 92 Spring Boot 2


11) Write Bean Configuration class – JTCWebConfig.java
12) Configure View Resolver in JTCWebConfig.java

@SpringBootApplication
public class JTCWebConfig implements WebMvcConfigurer{

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/myjsps/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}

13) Write Boot Main Class – StartMyBootApp.java

@SpringBootApplication(scanBasePackages = { "com.jtcindia.springboot" })
public class StartMyBootApp extends SpringBootServletInitializer {
public static void main(String[] args)
{ SpringApplication.run(StartMyBootApp.class,
args);
}

14) Run the Boot Application


You will see – Whitelabel Error Page means DS is Ready.

B) Develop the Usecase : show index page


http://localhost:12345/ => You are sending the request for /

15) Write index.jsp under WEB-INF/myjsps folder.

<!DOCTYPE html>
<html>
<body>
<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
</body>
</html>

www.jtcindia.org 93 Spring Boot 2


16) Write IndexController.java

@Controller
public class IndexController { @GetMapping("/")
public String showIndexPage()
{ System.out.println("IndexController - showIndexPage()");
return "index";
}
}

17) Run the Boot Application

18) Open the browser and hit http://localhost:12345/ If every thing fine you will see
index.jsp

C) Enable BootStarp:
19) Specify the Dependencies for Jquery and Bootstarp

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

20) Observe the following


a) bootstrap-4.3.1.jar
META-INF=> resources => webjars => bootstarp => 4.3.1 => css => bootstrap.min.css
META-INF=> resources => webjars => bootstarp => 4.3.1 => js => bootstrap.min.js

b) jquery-3.4.1.jar =>
META-INF=> resources => webjars => jquery => 3.4.1 => jquery.min.js

www.jtcindia.org 94 Spring Boot 2


21) Add the resource handler bean (to make your resources available in class path)
in JTCWebConfig
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META
-INF/resources/webjars/");
}

22) Include the css and js files in index.jsp.

<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">


<script src="webjars/jquery/3.4.1/jquery.min.js"></script>
<script src="webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>

23) Use Some BootStrap Classes in index.jsp

<h1 class="text-center"> Welcome to Jtcindia !!!</h1>

24) Run the Boot Application and Test

25) Open the browser and hit http://localhost:12345/


If every thing fine you will see Bootstrap Css styles applied in index.jsp

D) Develop the Usecase : show books


http://localhost:12345/showBooks

26) Add hyperlink in index.jsp

<h2 class="text-center"> <a href="showBooks"> Show Books </a></h2>

27) Write Book.java under com.jtcindia.springboot


28) Write BooksController.java under com.jtcindia.springboot
29) Write booksList.jsp under WEB-INF/myjsps
30) Run the Boot Application and Test
Open the browser and hit http://localhost:12345/

www.jtcindia.org 95 Spring Boot 2


Lab16: Files Required

1. index.jsp 2. booksList.jsp
3. Book.java 4. IndexController.java
5. BooksController.java 6. JTCWebConfig.java
7. StartMyBootApp.java 8. application.properties
9. pom.xml

1. index.jsp
<!DOCTYPE html>
<html>
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
<br/>
<h2 class="text-center"> <a href="showBooks"> Show Books </a></h2>

<script src="webjars/jquery/3.4.1/jquery.min.js"></script>
<script src="webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</body>
</html>

www.jtcindia.org 96 Spring Boot 2


2. booksList.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html> <head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
<div class="alert alert-primary" role="alert">
<h2 class="text-center"> Latest Books from Som Prakash Rai </h2>
</div>
<br/>
<table class="table table-striped table-bordered table-hover" style="font-size:20px;">
<thead class="thead-light ">
<tr> <th> Book Id </th>
<th> Book Name </th>
<th> Author</th>
<th> Price </th>
<th> Publications</th>
<th> </th>
<th> </th> </tr>
</thead>
<tbody>
<c:forEach var="mybook" items="${MyBooks}">
<tr>
<td> <a href="#"> ${mybook.bid} </a> </td>
<td> ${mybook.bname} </td>
<td> ${mybook.author} </td>
<td> ${mybook.price} </td>
<td> ${mybook.pub}</td>
<td> <button type="button" class="btn btn-success btn-lg">View Book</button> </td>
<td> <button type="button" class="btn btn-primary btn-lg">Edit Book</button> </td>
</tr>
</c:forEach>
<tbody>
</table>
</div>
<script src="webjars/jquery/3.4.1/jquery.min.js"></script>
<script src="webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>

www.jtcindia.org 97 Spring Boot 2


3. Book.java
spackage com.jtcindia.springboot;

import java.math.BigDecimal;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
public class Book
{ private Integer bid;
private String bname;
private String author;
private BigDecimal price;
private String pub;

public Book() {}
//Constructors
//Setters and Getters
}

4. IndexController.java
package com.jtcindia.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Controller
public class IndexController {

@GetMapping("/")
public String showIndexPage()
{ System.out.println("IndexController - showIndexPage()");
return "index";
}
}

www.jtcindia.org 98 Spring Boot 2


5. BooksController.java
package com.jtcindia.springboot;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Controller
public class BooksController {

@GetMapping("/showBooks")
public String getBooks(HttpSession session)
{ System.out.println(" BooksController - getBooks()");

List<Book> blist=new ArrayList<>();


Book mybook1=new Book(101,"Master Spring Boot","Som Prakash Rai
",BigDecimal.valueOf(10000.0),"JTC");

Book mybook2=new Book(102,"Master MicroServices","Som Prakash


Rai",BigDecimal.valueOf(10000.0),"JTC");
Book mybook3=new Book(103,"Master Angular","Som Prakash
Rai",BigDecimal.valueOf(10000.0),"JTC");

Book mybook4=new Book(104,"Master React ","Som Prakash


Rai",BigDecimal.valueOf(10000.0),"JTC");

Book mybook5=new Book(105,"Master Java Full Stack","Som Prakash


Rai",BigDecimal.valueOf(10000.0),"JTC");

blist.add(mybook1); blist.add(mybook2); blist.add(mybook3);


blist.add(mybook4); blist.add(mybook5);

session.setAttribute("MyBooks", blist);

return "booksList";
}
}

www.jtcindia.org 99 Spring Boot 2


6. JTCWebConfig.java
package com.jtcindia.springboot;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class JTCWebConfig implements
WebMvcConfigurer{ @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/myjsps/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-
INF/resources/webjars/");
}
}

7. StartMyBootApp.java
package com.jtcindia.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */

www.jtcindia.org 100 Spring Boot 2


@SpringBootApplication(scanBasePackages = { "com.jtcindia.springboot" }) public
class StartMyBootApp extends SpringBootServletInitializer {
public static void main(String[] args)
{ SpringApplication.run(StartMyBootApp.class,
args);
}
}

8. application.properties
server.port=12345

9. pom.xml
<project…>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab16</artifactId>
<version>1.0</version>
<name>MyLab16</name>
<url>https://www.jtcindia.org</url>

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

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

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

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

www.jtcindia.org 101 Spring Boot 2


<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

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

<build>
<finalName>MyLab16</finalName>
<plugins>

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

</project>

www.jtcindia.org 102 Spring Boot 2


Lab17: Spring MVC with Boot (using ThymeLeaf)
Working Steps:
1) Copy Lab16 as Lab17
2) Remove the WEB-INF under src/main/webapp ( So that all the JSP’s will be
deleted)
3) Remove ViewResolver from JTCWebConfig.java
4) Create templates folder under src/main/resources
5) Place index.html and booksList.html under templates
a)index.html (new in Lab17)
b)booksList.html (new in Lab17)

6) Add the following property in application.properties


server.port=54321
spring.thymeleaf.cache=false

7) Remove the following dependencies from pom.xml


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

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

8) Add the dependency for ThymeLeaf in pom.xml

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

www.jtcindia.org 103 Spring Boot 2


9) Make sure that all the Files as given below are updated correctly.

10) Run the Boot Application

11) Open the browser and hit http://localhost:54321/

Lab17: Files Required

1. index.html New in Lab17


2. booksList.html New in Lab17
3. Book.java Same as Lab16
4. IndexController.java Same as Lab16
5. BooksController.java Same as Lab16
6. JTCWebConfig.java Updated in Lab17
7. StartMyBootApp.java Same as Lab16
8. application.properties Updated in Lab17
9. pom.xml Updated in Lab17

1. index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

www.jtcindia.org 104 Spring Boot 2


<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
<br/>
<h2 class="text-center"> <a th:href="@{/showBooks}">Show Books</a> </h2>

<script src="webjars/jquery/3.4.1/jquery.min.js"></script>
<script src="webjars/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body> </html>
2. booksList.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
<div class="alert alert-primary" role="alert">
<h2 class="text-center"> Latest Books from Som Prakash Rai </h2>
</div>
<br/>
<table class="table table-striped table-bordered table-hover" style="font-size:20px;">
<thead class="thead-light ">
<tr> <th> Book Id </th>
<th> Book Name </th>
<th> Author</th>
<th> Price </th>
<th> Publications</th>
<th> </th> <th> </th>
</tr> </thead>
<tbody >
<tr th:each="mybook : ${session.MyBooks}">
<td th:text="${mybook.bid}"> </td>
<td th:text="${mybook.bname}"> </td>
<td th:text="${mybook.author}"></td>
<td th:text="${mybook.price}"> </td>
<td th:text="${mybook.pub}"> </td>
<td> <button type="button" class="btn btn-success btn-lg">View Book</button> </td>
<td> <button type="button" class="btn btn-danger btn-lg">Edit Book</button> </td>
</tr>
<tbody>
</table>
</div>
</body> </html>

www.jtcindia.org 105 Spring Boot 2


3. Book.java
4. IndexController.java
5. BooksController.java
6. JTCWebConfig.java
package com.jtcindia.springboot;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class JTCWebConfig implements
WebMvcConfigurer{ @Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-
INF/resources/webjars/");
}
}
7. StartMyBootApp.java
8. application.properties
server.port=54321
spring.thymeleaf.cache=false

9. pom.xml
<project…>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab17</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab17-jar</name>
<url>https://www.jtcindia.org</url>

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

www.jtcindia.org 106 Spring Boot 2


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

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

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

</dependencies>
<build>
<finalName>MyLab17</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

www.jtcindia.org 107 Spring Boot 2


 You can Develop as WAR file with Spring Boot
 WAR file is deployable application which can be deployed in any External Container to
run.

How to deploy War file to Tomcat8


1) Make Sure that JDK8 is Installed.

E:\JDK1.8.0
E:\JDK1.8.0\bin
E:\JDK1.8.0\lib

2) Set JAVA_HOME

set JAVA_HOME=E:\JDK1.8.0

3) Make Sure that Tomcat8.5 is Installed.

E:\Tomcat8.5
E:\Tomcat8.5\bin\tomcat8
E:\Tomcat8.5\lib\*.jar
E:\Tomcat8.5\conf\server.xml
E:\Tomcat8.5\conf\web.xml
E:\Tomcat8.5\conf\tomcat-users.xml *

Consider Tomcat port : 5050

4) Make sure that Maven is Installed.

E:\apache-maven-3.6.3
E:\apache-maven-3.6.3\bin\mvn
E:\apache-maven-3.6.3\lib\*.jar
E:\apache-maven-3.6.3\confg\settings.xml

5) Set Maven Path

set path=%path%; E:\apache-maven-3.6.3\bin;

6) Add an user with roles manager-gui and manager-script in tomcat-users.xml

<user username="SomPrakash"
password="SomPrakash"
roles="manager-gui,manager-script" />

www.jtcindia.org 108 Spring Boot 2


7) Add above Tomcat’s user in the Maven setting file, later Maven will use this user to
login Tomcat server.

<server>
<id>jtcTomcatServer</id>
<username>SomPrakash</username>
<password>SomPrakash</password>
</server>

8) Add Tomcat7 Maven Plugin in pom.xml

<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:5050/manager/text</url>
<server>jtcTomcatServer</server>
<path>/MyLab18</path>
</configuration>
</plugin>

Lab18: Spring MVC with Boot (WAR)


Working Steps:
1) Copy Lab16 as Lab18.

2) Update application.properties

No Properies Required

3) Update pom.xml (As Given in Lab18)


A) Add following 6 Dependencies
spring-boot-starter-web
jstl
standard
bootstrap
jquery
spring-boot-devtools

B) Add following 2 Plug-Ins


maven-compiler-plugin
tomcat7-maven-plugin

www.jtcindia.org 109 Spring Boot 2


4) Open Command Line and Start the Tomcat8.5
E:\Tomcat8.5\bin>tomcat8
5) Open Another Command Line and run the Maven Command
....\Lab18>mvn clean compile package tomcat7:deploy
6) Open Browser and type http://localhost:5050/MyLab18
Note : Maven Useful Commands
Deploy command => mvn tomcat7:deploy
UnDeploy command => mvn tomcat7:undeploy
ReDeploy command => mvn tomcat7:redeploy
Lab18: Files Required

1. index.jsp Same as Lab16


2. booksList.jsp Same as Lab16
3. Book.java Same as Lab16
4. IndexController.java Same as Lab16
5. BooksController.java Same as Lab16
6. JTCWebConfig.java Same as Lab16
7. StartMyBootApp.java Same as Lab16
8. application.properties Updated in Lab18
9. pom.xml Updated in Lab18

www.jtcindia.org 110 Spring Boot 2


8. application.properties
No Properies

9. pom.xml
<project…>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab18</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>Lab18-jar</name>
<url>https://www.jtcindia.org</url>

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

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

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>

<dependency>

www.jtcindia.org 111 Spring Boot 2


<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

</dependencies>
<build>
<finalName>MyLab18</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<url>http://localhost:5050/manager/text</url>
<server>jtcTomcatServer</server>
<path>/MyLab18</path>
<update>true</update>
</configuration>
</plugin>
</plugins>

</build>
</project>

www.jtcindia.org 112 Spring Boot 2


Lab19: Files required
1. index.jsp 2. booksList.jsp
3. viewBook.jsp 4. addEditBook.jsp
5. IndexController.java 6. BookController.java
7. BookService.java 8. BookServiceImpl.java
9. BookDAO.java 10. BookDAOImpl.java
11. Book.java 12. JTCWebConfig.java
13. MyBootWebApplication.java 14. application.properties
15. pom.xml

viewBook.jsp

1. index.jsp
<html>
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="card-header">
<h2 class="text-center">Welcome to JTC Bookstore</h2>
<h4 class="text-center"> Best Books and Best Videos</h4>
</div>
<br/><br/>
<div class="container" align="center">
<h2> <a href="showAllBooks">Display All Books</a> </h2>
</div>
</body>
</html>

www.jtcindia.org 113 Spring Boot 2


2. bookList.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="card-header">
<h2 class="text-center">Welcome to JTC Bookstore</h2>
<h4 class="text-center"> Best Books and Best Videos</h4>
</div>
<br/><br/>
<div class="container" >
<table class="table table-striped table-bordered" style="font-size:20px;font-weight:bold;">
<tr>
<th>Book ID</th>
<th>Book Name</th>
<th>Author</th>
<th>Price</th>
<th>Category</th>
<th>Publications </th>
<th colspan="2" align="center">
<form:form action="addEditBookForm">
<input type="hidden" name="bookId" value="0"/>
<input type="submit" value=" Add New Book " class="btn btn-success btn-lg"/>
</form:form> </th>
</tr>
<c:forEach var="mybook" items="${MyBooksList}">
<tr>
<td> <a href="viewBook?bookId=${mybook.bid }"> ${mybook.bid } </a> </td>
<td>${mybook.bname }</td>
<td>${mybook.author }</td>
<td>${mybook.price }</td>
<td>${mybook.category }</td>
<td>${mybook.pub }</td>
<td>
<form:form action="addEditBookForm">
<input type="hidden" name="bookId" value="${mybook.bid }"/>
<input type="submit" value=" Edit " class="btn btn-primary btn-lg"/>
</form:form>
</td>

www.jtcindia.org 114 Spring Boot 2


<td>
<form:form action="deleteBook">
<input type="hidden" name="bookId" value="${mybook.bid }"/>
<input type="submit" value=" Delete " class="btn btn-danger btn-lg"/>
</form:form>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>

3. viewBook.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html> <head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="card-header">
<h2 class="text-center">Welcome to JTC Bookstore</h2>
<h4 class="text-center"> Best Books and Best Videos</h4>
</div>
<br/><br/>
<div class="container" >
<table class="table table-striped table-bordered" style="font-size:20px;font-weight:bold;">
<tr>
<td align="center" colspan="3"> Book Details</td>
</tr>
<tr>
<td> Book Id</td>
<td> ${MyBook.bid} </td>
</tr>
<tr>
<td> Book Name</td>
<td> ${MyBook.bname} </td>
</tr>
<tr>
<td>Author</td>
<td> ${MyBook.author} </td>
</tr>

www.jtcindia.org 115 Spring Boot 2


<tr>
<td>Price</td>
<td>${MyBook.price} </td>
</tr>
<tr>
<td>Category</td>
<td>${MyBook.category} </td>
</tr>
<tr>
<td>Publications</td>
<td>${MyBook.pub} </td>
</tr>
</table> </div>
<div align="center">
<h2> <a href="showAllBooks">Goto Book Home</a> </h2>
</div>
</body> </html>

4. addEditBook.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
<title>JTC Bookstore</title>
<link href="webjars/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="card-header">
<h2 class="text-center">Welcome to JTC Bookstore</h2>
<h4 class="text-center"> Best Books and Best Videos</h4>
</div>
<br/><br/>
<div align="center" class="container">
<form:form action="saveUpdateBook" method="post" modelAttribute="mybook">
<table class="table" style="font-size:20px;font-weight:bold;">
<tr>

<c:if test="${OpType eq 'ADD' }">


<td align="center" colspan="3"> <h2> Add New Book </h2></td>
</c:if>
<c:if test="${OpType eq 'UPDATE' }">
<td align="center" colspan="3"> <h2> Update Book </h2></td>
</c:if>

www.jtcindia.org 116 Spring Boot 2


</tr>
<tr>
<td> Book Name</td>
<td><form:input path="bname" class="form-control form-control-lg"/></td>
<td><font color=red size=4><form:errors path="bname" /></font></td>
</tr>
<tr>
<td>Author</td>
<td><form:input path="author" class="form-control form-control-lg"/></td>
<td><font color=red size=4><form:errors path="author" /></font></td>
</tr>
<tr>
<td>Price</td>
<td><form:input path="price" class="form-control form-control-lg"/></td>
<td><font color=red size=4><form:errors path="price" /></font></td>
</tr>
<tr>
<td>Category</td>
<td><form:input path="category" class="form-control form-control-lg"/></td>
<td><font color=red size=4><form:errors path="category" /></font></td>
</tr>
<tr>
<td>Publications</td>
<td><form:input path="pub" class="form-control form-control-lg"/></td>
<td><font color=red size=4><form:errors path="pub" /></font></td>
</tr>
<tr>
<td align="center" colspan="3">
<input type="hidden" name="OpType" value="${OpType}"/>
<c:if test="${OpType eq 'ADD' }">
<input type="submit" value="Add New Book" class="btn btn-primary btn-lg"/>
</c:if>
<c:if test="${OpType eq 'UPDATE' }">
<input type="submit" value="Update Book" class="btn btn-primary btn-lg"/>
<form:hidden path="bid" />
</c:if>
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

www.jtcindia.org 117 Spring Boot 2


5. IndexController.java
package com.jtcindia.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
@Controller
public class IndexController {

@GetMapping("/")
public String showIndexPage() {
System.out.println("---------showIndexPage----------");
return "index";
}

6. BookController.java
package com.jtcindia.spring.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.jtcindia.spring.entity.Book;
import com.jtcindia.spring.service.BookService;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@Controller
@SessionAttributes("MyBooksList")
public class BookController {

www.jtcindia.org 118 Spring Boot 2


@Autowired
BookService bookService;

@GetMapping("/showAllBooks")
public String showBooksList(Model model) {
System.out.println("-------BookController--showBooksList()---------- ");
List<Book> blist=bookService.getAllBooks();
model.addAttribute("MyBooksList", blist);

return "booksList";
}

@PostMapping("/addEditBookForm")
public String addBookForm(@RequestParam("bookId") Integer bookId,Model model)
{ System.out.println("-------BookController--addEditBookForm()-------- ");
System.out.println(bookId);
Book book=new Book();
String opType="ADD";
if(bookId!=0) {
book=bookService.getBookById(bookId);
opType="UPDATE";
}
model.addAttribute("mybook", book);
model.addAttribute("OpType", opType);

return "addEditBook";
}

@PostMapping("/saveUpdateBook")
public String saveUpdateBook(@Valid @ModelAttribute("mybook") Book
book,BindingResult result,Model model,HttpServletRequest req) {
System.out.println("-------BookController--saveUpdateBook()---------- ");
String opType=req.getParameter("OpType");
System.out.println(opType); if(opType.equals("ADD"))
{
bookService.addBook(book);
}
if(opType.equals("UPDATE"))
{ bookService.updateBook(book);
}

List<Book> blist=bookService.getAllBooks();
model.addAttribute("MyBooksList", blist);

return "booksList";
}

www.jtcindia.org 119 Spring Boot 2


@PostMapping("/deleteBook")
public String deleteBook(@RequestParam("bookId") Integer bookId,Model model)
{ System.out.println("-------BookController--deleteBook()-------- ");
bookService.deleteBook(bookId);
List<Book> blist=bookService.getAllBooks();
model.addAttribute("MyBooksList", blist);

return "booksList";
}

@GetMapping("/viewBook")
public String viewBook(@RequestParam("bookId") String bookId,Model model)
{ System.out.println("-------BookController--viewBook()-------- ");
System.out.println(bookId);
Book book=bookService.getBookById(Integer.parseInt(bookId));
model.addAttribute("MyBook", book);

return "viewBook";
}

7. BookService.java
package com.jtcindia.spring.service;

import java.util.List;
import com.jtcindia.spring.entity.Book;
/*
* @Author : Som Prakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
public interface BookService {
public List<Book> getAllBooks();
public Book getBookById(Integer bid);
public void addBook(Book book);
public void updateBook(Book book);
public void deleteBook(Integer bid);
}

8. BookServiceImpl.java
package com.jtcindia.spring.serviceimpl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jtcindia.spring.dao.BookDAO;

www.jtcindia.org 120 Spring Boot 2


import com.jtcindia.spring.entity.Book;
import com.jtcindia.spring.service.BookService;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
@Service
public class BookServiceImpl implements BookService{

@Autowired
BookDAO bookDAO;

@Override
public List<Book> getAllBooks() {
System.out.println("-----BookServiceImpl--getAllBooks()---------- ");
return bookDAO.getAllBooks();
}
@Override
public Book getBookById(Integer bid) {
System.out.println("-----BookServiceImpl--getBookById()---------- ");
return bookDAO.getBookById(bid);
}
@Override
public void addBook(Book book) {
System.out.println("-----BookServiceImpl--addBook()---------- ");
bookDAO.addBook(book);
}

@Override
public void updateBook(Book book) {
System.out.println("-----BookServiceImpl--updateBook()---------- ");
bookDAO.updateBook(book);
}

@Override
public void deleteBook(Integer bid) {
System.out.println("-----BookServiceImpl--deleteBook()---------- ");
bookDAO.deleteBook(bid);
}
}

www.jtcindia.org 121 Spring Boot 2


9. BookDAO.java
package com.jtcindia.spring.dao;

import java.util.List;
import com.jtcindia.spring.entity.Book;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
public interface BookDAO{
public List<Book> getAllBooks();
public Book getBookById(Integer bid);
public void addBook(Book book);
public void updateBook(Book book);
public void deleteBook(Integer bid);
}

10. BookDAOImpl.java
package com.jtcindia.spring.daoimpl;

import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.jtcindia.spring.dao.BookDAO;
import com.jtcindia.spring.entity.Book;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
@Repository
@Transactional
public class BookDAOImpl implements BookDAO{

@Autowired
EntityManager entityManager;

public List<Book> getAllBooks(){


System.out.println("-----BookDAOImpl--getAllBooks()---------- ");
String jpaql = "from Book book";
List<Book> list=entityManager.createQuery(jpaql) .getResultList();
return list;
}

www.jtcindia.org 122 Spring Boot 2


public Book getBookById(Integer bid) {
System.out.println("-----BookDAOImpl--getBookById()---------- ");
return entityManager.getReference(Book.class,bid);
}
public void addBook(Book book) {
System.out.println("-----BookDAOImpl--addBook()----------");
entityManager.persist(book);
}
public void deleteBook(Integer bid) {
System.out.println("-----BookDAOImpl--deleteBook()----------");
Book book=entityManager.getReference(Book.class,bid);
entityManager.remove(book);
}

public void updateBook(Book book) {


System.out.println("-----BookDAOImpl--updateBook()---------- ");
entityManager.merge(book);
}
}

11. Book.java
package com.jtcindia.spring.entity;

import java.math.BigDecimal;
import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
@Entity
@Table(name="mybooks")
public class Book {
@Id
@Column(name="bid")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer bid;

@Column(name="bname")
@NotEmpty(message = "Book Name is Required")
@Size(min=5,max=20,message="Name length must be between 5 and 20")
private String bname;

www.jtcindia.org 123 Spring Boot 2


@Column(name="author")
@NotEmpty(message = "Author is Required")
@Size(min=3,max=10,message="Name length must be between 3 and 10")
private String author;

@Column(name="price")
@NotNull(message = "Price is Required")
@Min(value=500, message="Price must be min : 500")
@Max(value=1500, message="Price must be max : 1500")
private BigDecimal price;

@Column(name="category")
@NotEmpty(message = "Category is Required")
private String category;

@Column(name="pub")
@NotEmpty(message = "Pub is Required")
private String pub;

public Book() {
}
//Constructors
//Setters and Getters

@Override
public String
toString() {
return "[" + bid + " , " + bname + " , " + author + " , " + price + " , " + category + " , " + pub+ "]";
}
}
12. JTCWebConfig.java
package com.jtcindia.spring.config;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.*;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */

www.jtcindia.org 124 Spring Boot 2


@EnableWebMvc
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.jtcindia.spring" })
@EntityScan(basePackages = { "com.jtcindia.spring.entity" })
public class JTCWebConfig implements
WebMvcConfigurer{ @Bean
public InternalResourceViewResolver viewResolver()
{ InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/myjsps/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{ registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-
INF/resources/webjars/");
}
}

13. StartMyBootApp.java
package com.jtcindia.spring.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/*
* @Author : Som Prakash Rai
* @Company : Jtcindia
* @Website : www.jtcindia.org
* */
@SpringBootApplication(scanBasePackages = {"com.jtcindia.spring"}) @EnableWebMvc
public class StartMyBootApp extends
SpringBootServletInitializer{ public static void
main(String[] args) {
SpringApplication.run(StartMyBootApp.class, args);
}
}

14. application.properties
server.port=5599

logging.level.root=INFO
logging.pattern.console=%-5level %logger{36} - %msg%n

www.jtcindia.org 125 Spring Boot 2


spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb
spring.datasource.username=root
spring.datasource.password=SomPrakash

spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

15. pom.xml
<project ….>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab19</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab19-jar</name>
<url>https://www.jtcindia.org</url>

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

<dependencies>

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

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

<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.3.1</version>
</dependency>

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>

www.jtcindia.org 126 Spring Boot 2


<version>3.4.1</version>
</dependency>

<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

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

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

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

www.jtcindia.org 127 Spring Boot 2


Lab20: Building a First RESTful Web Service
Lab20:Working Steps:

A) Setup the Project:


1. Copy Lab16 as Lab20.

2. Delete all the files except the following 4 files.


a) JTCWebConfig.java
b) StartMyBootApp.java
c) application.properties
d) pom.xml

3. Update pom.xml
a) Add the following dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

4. Update application.properties
a. Add the following Properties in application.properties

spring.application.name=my-hello- app
server.port=12345

5. Update JTCWebConfig.java

@SpringBootApplication
public class JTCWebConfig {

6. Update StartMyBootApp.java

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

www.jtcindia.org 130 Spring Boot 2


7. Build the Boot App.

B) Develop RESTful Web Service

8. Create a Resource Representation Class - Hello

public class Hello {

String name;
String message;

//Constructors
//Setters and Getters
}

9. Create a Resource Controller called HelloController

@RestController
public class HelloController {

@GetMapping("/myhello")
public String getMessage1() {
....
}

@GetMapping("/myhello/{name}")
public String getMessage2(@PathVariable String name) {
....
}

@GetMapping("/myhello/{name}/{email}")
public String getMessage3(@PathVariable String name,@PathVariable String email) {
....
}

@GetMapping(value="/hello1/{name}",produces = "application/json" )
public Hello getMessage4(@PathVariable String name) {
....
}

@GetMapping(value = "/hello2/{name}", produces = "application/xml")


public Hello getMessage5(@PathVariable String name) {

@RequestMapping(value = "/hello3/{name}", method = RequestMethod.GET)


public Hello getMessage6(@PathVariable("name") String name) {
....
}

www.jtcindia.org 131 Spring Boot 2


@RequestMapping(value = "/hello4/{name}", method = RequestMethod.GET,produces =
"application/json")
public Hello getMessage7(@PathVariable("name") String name) {
....
}
}

C) ​ Test Rest API with Browser.


10. Hit the following urls from Browser

http://localhost:12345/myhello
http://localhost:12345/myhello/somprakash
http://localhost:12345/myhello/somprakash/som@jtc
http://localhost:12345/hello1/somprakash
http://localhost:12345/hello2/somprakash
http://localhost:12345/hello3/somprakash
http://localhost:12345/hello4/somprakash

D) ​ Test Rest API with CURL.


A. Download CURL from https://curl.haxx.se/download.html
You will get zip: curl-7.67.0.zip

B. Extract to E: drive.
Now curl home is E:\curl-7.67.0

C. Goto E:\curl-7.67.0 and type the following


curl -v -X GET localhost:12345/myhello
curl -v -X GET
localhost:12345/myhello/som
curl -v -X GET
localhost:12345/myhello/som/som@jtc curl -v -X
GET localhost:12345/hello1/ somprakash
curl -v -X GET localhost:12345/hello2/
somprakash curl -v -X GET
localhost:12345/hello3/ somprakash curl -v -X
GET localhost:12345/hello4/ somprakash

d) Test Rest API with Postman


try yourself

www.jtcindia.org 132 Spring Boot 2


Lab20: Files required
1. HelloController.java 2. Hello.java
3. JTCWebConfig.java 4. StartMyBootApp.java
5. application.properties 6. pom.xml

1. HelloController.java
package com.jtcindia.springboot;

import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
/*
* @Author : Somprakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@RestController
public class HelloController {

@GetMapping("/myhello")
public String getMessage1() {
System.out.println("HC-getMessage1()");
return "I am getMessage1";
}

@GetMapping("/myhello/{name}")
public String getMessage2(@PathVariable String name)
{ System.out.println("HC-getMessage2()");
String msg="Hello "+name +" !!! - I am getMessage2";
return msg;
}

@GetMapping("/myhello/{name}/{email}")
public String getMessage3(@PathVariable String name,@PathVariable String email)
{ System.out.println("HC-getMessage3()");
System.out.println(name+"\t"+email);
String msg="Hello "+name +" !!! - I am getMessage3";
return msg;
}

www.jtcindia.org 133 Spring Boot 2


@GetMapping(value="/hello1/{name}",produces = "application/json" )
public Hello getMessage4(@PathVariable String name) {
System.out.println("HC-getMessage4()");
Hello hello=new Hello();
hello.setName(name);
String msg="Hello "+name +" !!! - I am getMessage4";
hello.setMessgae(msg);
return hello;
}

@GetMapping(value = "/hello2/{name}", produces = "application/xml")


public Hello getMessage5(@PathVariable String name) {
System.out.println("HC-getMessage5()");
Hello hello=new Hello();
hello.setName(name);
String msg="Hello "+name +" !!! - I am getMessage5";
hello.setMessgae(msg);
return hello;
}

@RequestMapping(value = "/hello3/{name}", method = RequestMethod.GET)


public Hello getMessage6(@PathVariable("name") String name) {
System.out.println("HC-getMessage6()");
Hello hello=new Hello();
hello.setName(name);
String msg="Hello "+name +" !!! - I am getMessage6";
hello.setMessgae(msg);
return hello;
}

@RequestMapping(value = "/hello4/{name}", method = RequestMethod.GET,produces


= "application/json")
public Hello getMessage7(@PathVariable("name") String name)
{ System.out.println("HC-getMessage7()");
Hello hello=new Hello();
hello.setName(name);
String msg="Hello "+name +" !!! - I am getMessage7";
hello.setMessage(msg);
return hello;
}
}

www.jtcindia.org 134 Spring Boot 2


2. Hello.java
package com.jtcindia.springboot;

import javax.xml.bind.annotation.XmlRootElement;
/* * @Author : Somprakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@XmlRootElement
public class Hello {
String name;
String message;
//Constructors
//Setters and Getters
}

3. JTCWebConfig.java
package com.jtcindia.springboot;

import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Somprakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class JTCWebConfig { }

4. StartMyBootApp.java
package com.jtcindia.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : Somprakash Rai
* @Company : JTCINDIA
* @Website : www.jtcindia.org
* */
@SpringBootApplication
public class StartMyBootApp {
public static void main(String[] args)
{ SpringApplication.run(StartMyBootApp.class,
args);
}
}

www.jtcindia.org 135 Spring Boot 2


5. application.properties
spring.application.name=my-hello- app
server.port=12345

6. pom.xml
<project…>
<modelVersion>4.0.0</modelVersion>
<groupId>com.jtcindia.springboot</groupId>
<artifactId>Lab20</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Lab20-jar</name>
<url>https://www.jtcindia.org</url>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.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-devtools</artifactId>
</dependency>

</dependencies>
<build>
<finalName>MyLab20</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

www.jtcindia.org 136 Spring Boot 2

You might also like