9 Spring Boot
9 Spring Boot
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.
6. Externalized Configurations
7. YAML Support
8. Embedded Containers
9. Actuators
<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>
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 {
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) );
}
}
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;
//Constructors
//Setters and Getters
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;
}
}
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>
<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>
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.
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<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>
#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
@Configuration
@ComponentScan(basePackages = {"com.jtcindia.springboot"})
public class JTCAppConfig {
9) Write the DAO and its Implementation class (Copy from Lab1)
CustomerDAO.java
CustomerDAOImpl.java
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;
@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);
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
<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>
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.
Q17) What happens when I am not providing Any DataSource after excluding Hikari?
Ans:
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
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>
<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>
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
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>
<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>
3) Update application.properties
A) Add HIkari Properties as follows
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
spring.datasource.tomcat.initialSize=5
spring.datasource.tomcat.max-active=25
spring.datasource.dbcp2.initial-size=5
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true
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>
<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>
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;
SpringApplication.run(MyBootApp.class, args);
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
@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";
#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
<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>
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.
Q30) What happens internally when you run the Spring Boot Application?
Ans:
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;
@Autowired
Hello hello;
@Autowired
Hai hai;
@Autowired
HelloService helloService;
@Autowired
HelloDAO helloDAO;
@Autowired
DataSource myds;
hello.show();
hai.show();
helloService.show();
helloDAO.show();
Connection con=myds.getConnection();
DatabaseMetaData dbmd=con.getMetaData();
System.out.println(dbmd.getDatabaseProductName());
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();
}
}
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()");
}
}
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>
<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>
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{
@Autowired
CustomerDAO cdao;
List<Customer> list1=cdao.getAllCustomers();
list1.forEach(cust -> System.out.println(cust));
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 ;
}
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);
}
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();
factory.setHibernateProperties(props); //1
factory.setDataSource(dataSource); //2
factory.setPackagesToScan("com.JTCINDIA.springboot"); //3
return factory;
}
@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>
<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>
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;
}
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() {
return jpaVendor;
}
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);
}
}
▪ We can use JPA with Spring Boot without configure EntityManagerFactory and
JpaTransactionManager in Lab10 because these are Auto-Configured by Spring
Boot.
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
DataSource ds;
JdbcTemplate jtemp;
NamedParameterJdbcTemplate njtemp;
EntityManagerFactory emf;
JpaTranactionManager txManager;
@Autowired(required = false) No
SessionFactory sf;
@Autowired(required = false) No
HibernateTemplate htemp;
@Autowired(required = false) No
HibernateTransactionManager txManager;
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 {
@Autowired
CustomerDAO cdao;
// 1. addCustomer
Customer cust1 = new Customer("som", "som@jtc", 1234,
"Noida"); cdao.addCustomer(cust1);
// 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);
//14.getCidByPhone
int cid = cdao.getCidByPhone(123);
System.out.println(cid);
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);
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;
}
}
<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>
@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;
}
}
@SpringBootApplication(scanBasePackages = { "com.jtcindia.springboot" })
public class StartMyBootApp extends SpringBootServletInitializer {
public static void main(String[] args)
{ SpringApplication.run(StartMyBootApp.class,
args);
}
<!DOCTYPE html>
<html>
<body>
<h1 class="text-center"> Welcome to Jtcindia !!!</h1>
</body>
</html>
@Controller
public class IndexController { @GetMapping("/")
public String showIndexPage()
{ System.out.println("IndexController - showIndexPage()");
return "index";
}
}
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>
b) jquery-3.4.1.jar =>
META-INF=> resources => webjars => jquery => 3.4.1 => jquery.min.js
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>
<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>
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";
}
}
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()");
session.setAttribute("MyBooks", blist);
return "booksList";
}
}
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
* */
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>
<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>
<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-thymeleaf</artifactId>
</dependency>
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>
<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>
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>
<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>
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
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 *
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
<user username="SomPrakash"
password="SomPrakash"
roles="manager-gui,manager-script" />
<server>
<id>jtcTomcatServer</id>
<username>SomPrakash</username>
<password>SomPrakash</password>
</server>
<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>
2) Update application.properties
No Properies Required
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>
<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>
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>
<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>
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>
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>
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 {
@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";
}
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;
@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);
}
}
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;
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;
@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
* */
@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
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>
<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>
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);
}
}
String name;
String message;
//Constructors
//Setters and Getters
}
@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) {
....
}
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
B. Extract to E: drive.
Now curl home is E:\curl-7.67.0
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;
}
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);
}
}
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>