Spring Boot
Spring Boot
>File>New>other>Search Maven > Choose “Maven Project” >Next>Choose Checkbox > Create Simple
Project> Next>Enter Details Like>
groupId: org.sathyatech
Version: 1.0
>Finish
a. Parent Project
b. Properties
c. Dependencies
d. Build-plugin
>right click on src/main/resources > new > other > Search with “File” > Choose File > next> otherName
Ex: application.properties
>Finish
#5 Run DemoApp (Starter Class) and goto browser, Enter URL like,
http://localhost:2018/
pom.xml Code:
<project>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=2018
Starter Class
package com.app;
@SpringBootApplication
main(String[] args){
SpringBootApplication.run(DemoApp.class,arg);
SpringBoot ReST webservices are used to define application logic one time which can be reusable to any
client/UI applications.
Here UI/Client can be WebApplication (developed using Angular, Spring UI etc…) or Mobile application
(developed using Android UI) else it can be 3rd Party Integration (link with Payment Gateway, link with
Online Shops, link with other application).
#2 Supports also XML, but not used in real-time b’coz of performance issue.
An Endpoint is used to access one Service Provider (method) which contains details like URL (Path), Type
(GET, POST, PUT, DELETE…), Input, Output details.
Path = /getBal/{accId}
Type= GET
#1 write one public class with package and apply annotation at class level
@RestController
#2 Define one method in class with some logic (return type can be String, class, collection, etc.)
**Path is case-sensitive
#4 To readData from application.properties define one variable in class level and use @Value(“$,key-”)
Code:
Under src/main/java
package com.app;
@RestController
@GetMapping(“/show”)
return ”Hello”;
@Value(“$,server.port-”)
@GetMapping(“/Show”)
Steps:
#1 Go to start.spring.io
groupId: com.app;
artifactId: AppOne
Dependencies: web
server.port=2018
#6 Run Starter class and enter URL
http://localhost:2018/show
Note:
If we try to run 2nd process on existed port number, exception is BindException: Address already in use:
bind
#4 If application is not under basePackage (Spring Boot Starter class package or its sub packeges) then it
will not be detected. So Object of your class cannot be created.
#5 To provide multiple base-packages to select all classes use annotation
@ComponentScan(basePackeges=,“pack1”,”pack2”,””-)
Ex:
package com.app;
@SpringBootApplication
@ComponentScan(basePackeges=,“com.one”,”app”,”ab”-)
main(String[] args){
SpringApplication.run(AppProvider,class,args);
Every SpringBoot Rest Application works by default with JSON Global Data Format.
,“key”:Value}
Every Java object can be converted to JSON format even reverse also possible.
JACKSON is an API used by SpringBoot with auto-conversion feature to convert Java Object to JSON
format.
Example:
RestController method return type can be primitive (String), Class type, Collection Type.
Example:
http://spring.io/tools/sts/all
“…/sts-bundle/sts-3.9.4.RELEASE”
package com.example.app.controller;
@RestController
@GetMapping(“/show”)
emp.setEmpId(100);
emp.setEmpName(“AA”);
emp.setEmpSal(12.36);
return emp;
@GetMapping(“/showAll”)
return emps;
package com.example.app.model;
//set-get, toString
http://localhost:2018/show
http://localhost:2018/showAll
Example: SpringWebMvcApplication
SpringWebMvcApplication.java
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringWebMvcAppApplication.class, args);
ServletIntializer.java
package com.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringWebMvcAppApplication.class);
Employee.java
package com.app.model;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="emptab")
@Id
@Column(name="eid")
@GeneratedValue(generator="empgen")
@GenericGenerator(name="empgen",strategy="increment")
@Column(name="ename")
@Column(name="email")
@Column(name="egen")
@Column(name="addr")
@CollectionTable(
@Column(name="idType")
@Column(name="idnum")
//alt+shift+S,O(De-select-all>OK)
public Employee() {
super();
super();
this.empId = empId;
public Employee(Integer empId, String empName, String empMail, String empGen, String
empAddr, List<String> empLangs,
super();
this.empId = empId;
this.empName = empName;
this.empMail = empMail;
this.empGen = empGen;
this.empAddr = empAddr;
this.empLangs = empLangs;
this.empIdType = empIdType;
this.empIdNum = empIdNum;
//alt+shift+S,R (selectAll>OK)
return empId;
this.empId = empId;
return empName;
this.empName = empName;
return empMail;
}
public void setEmpMail(String empMail) {
this.empMail = empMail;
return empGen;
this.empGen = empGen;
return empAddr;
this.empAddr = empAddr;
return empLangs;
this.empLangs = empLangs;
return empIdType;
}
public void setEmpIdType(String empIdType) {
this.empIdType = empIdType;
return empIdNum;
this.empIdNum = empIdNum;
//alt+shift+S,S(OK)
@Override
+ empIdNum + "]";
EmployeeRepository.java
package com.app.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.app.model.Employee;
}
IEmployeeService.java
package com.app.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.app.model.Employee;
//special methods
EmployeeServiceImpl.java
package com.app.service.impl;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.app.model.Employee;
import com.app.repo.EmployeeRepository;
import com.app.service.IEmployeeService;
@Service
@Autowired
@Override
return repo.save(emp).getEmpId();
@Override
repo.deleteById(empId);
@Override
return repo.existsById(empId);
@Override
Optional<Employee> emp=repo.findById(empId);
if(emp.isPresent())
return emp.get();
else
return null;
@Override
List<Employee> emps=repo.findAll();
Collections.sort(emps, (e1,e2)->e1.getEmpId()-e2.getEmpId());
return emps;
//special methods
@Override
return repo.findAll(pageable);
EmployeeValidator.java
package com.app.validator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.app.model.Employee;
@Component
return Employee.class.equals(clazz);
@Override
Employee e=(Employee)target;
if(e.getEmpName()==null || "".equals(e.getEmpName().trim())){
if(StringUtils.isEmpty(e.getEmpMail()) ||
StringUtils.containsWhitespace(e.getEmpMail())) {
if(StringUtils.isEmpty(e.getEmpGen()) ||
StringUtils.containsWhitespace(e.getEmpGen())) {
if(StringUtils.isEmpty(e.getEmpAddr()) ||
StringUtils.containsWhitespace(e.getEmpAddr())) {
if(e.getEmpLangs()==null || e.getEmpLangs().isEmpty()) {
if(StringUtils.isEmpty(e.getEmpIdType())) {
errors.rejectValue("empIdType",null, "Please Choose one Type !!");
if(StringUtils.isEmpty(e.getEmpIdNum()) ||
StringUtils.containsWhitespace(e.getEmpIdNum())) {
EmployeeController.java
package com.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.app.model.Employee;
import com.app.service.IEmployeeService;
import com.app.validator.EmployeeValidator;
@Controller
@Autowired
@Autowired
@GetMapping("/reg")
return "EmployeeRegister";
@PostMapping("/insert")
validator.validate(employee, errors);
if(errors.hasErrors()) {
map.addAttribute("employee", employee);
}else {
Integer empId=service.saveEmployee(employee);
//clear form
}
return "EmployeeRegister";
@GetMapping("/viewAll")
List<Employee> emps=service.getAllEmployees();
map.addAttribute("emps", emps);
return "EmployeeData";
@GetMapping("/viewPage")
public String
showPageData(@PageableDefault(page=0,size=3,sort="empId",direction=Direction.ASC) Pageable
pageable,ModelMap map) {
Page<Employee> emps=service.getAllEmployees(pageable);
map.addAttribute("page", emps);
return "EmployeeData";
application.properties
server.port=2626
#ViewResolver Details
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
#Connection Details
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
#Hibernate Details
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#Pool Details
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=15
spring.datasource.hikari.pool-name=HikariCP
EmployeeRegister.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<h1>Welcome to Employee</h1>
<pre>
<form:errors path="empName"/>
<form:errors path="empMail"/>
<form:errors path="empGen"/>
<form:errors path="empAddr"/>
<form:errors path="empLangs"/>
ID : <form:select path="empIdType">
<form:option value="">--select--</form:option>
<form:option value="AADHAR">AADHAR</form:option>
<form:option value="OTHER">OTHER</form:option>
</form:select>
<form:errors path="empIdType"/>
</pre>
</form:form>
${message}
</body>
</html>
EmployeeData.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Employee Data</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>ADDRESS</th>
<th>LANGUAGES</th>
<th>ID</th>
<th>NUMBER</th>
</tr>
<tr>
</tr>
</c:forEach>
</table>
<c:if test="${!page.isFirst()}">
<a href="?page=0">First</a>
</c:if>
<c:if test="${page.hasPrevious()}">
<a href="?page=${page.getNumber()-1}">Previous</a>
</c:if>
<c:forEach begin="0" end="${page.getTotalPages()-1}" var="i">
<c:choose>
${i+1}
</c:when>
<c:otherwise>
<a href="?page=${i}">${i+1}</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${page.hasNext()}">
<a href="?page=${page.getNumber()+1}">Next</a>
</c:if>
<c:if test="${!page.isLast()}">
<a href="?page=${page.getTotalPages()-1}">Last</a>
</c:if>
</body>
</html>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringWebMvcApp</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringWebMvcApp</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ResponseEntity as return Type of RestController method:
In application, development we should never use String, classType, Collection as return Type, which may
give incomplete output.
Provide these details as ResponseEntity return Type which contains body and status.
1xx Information
2xx Success
3xx redirect
**ResponseEntity<T> must have body of T type (T = DataType specified while using or coding in method)
We can use ? symbol at method return level or declaration level only. (not at object creation (new
creation level)).
Code Template:
package com.app.controller;
@RestController
@GetMapping(“/showget”)
try{
//logic
status = HttpStatus.ok;//200- success
}catch(Exception e){
status = HttpStatus.BAD_REQUEST;
return resp;
Code: -
package com.app.controller;
@RestController
@GetMapping(“/showGet”)
@PostMapping(“/showPost”)
public ResponseEntity<String> showPost(){
@PutMapping(“/showPut”)
@DeleteMapping(“/showDelete”)
1. ../show/20/ab (404 not found) – b’z name is static and we are giving dynamic.
2. ../show/20.36/name (BAD_REQUEST 400)
3. ../show/9/name (Ok 200)
4. ../show/ab/name (BAD_REQUEST 400)
5. ../show/10/10 (404 NOT FOUND)
Syntax:#1
@PathVariable(“key”)DT localVar
Syntax:#2
@PathVariable DT Key
Here,
Example:
package com.app.provider;
@RestController
@GetMapping(“/Show/,eid-”)
@GetMapping(“/Show/,eid-/,ename-”)
@GetMapping(“/Show/,eid-/,ename-/,esal-”)
@GetMapping(“/Show/eid/ename/esal”)
return “Hello::None”;
If method is GET type and request in non-GET (ex: POST) then this error will occure.
Http-Status-400: BAD_REQUEST
@RequestBody:
It is used to convert input data (JSON) provided in HttpRequest Body are will be converted to object
format for request method.
**GET will not support this operation only PUT, DELETE and POST also supports.
Flow:
Example:
package com.app.model;
package com.app.provider;
@RestController
@PostMapping(“/show”)
return “Hello:”+emp.getEmpId()+”,”+emp.getEmpName+”,”+emp.getEmpSal();
}
Example: SpringReSTMySQL
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.app</groupId>
<artifactId>Demo</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>SpringRestMySQL</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#Server Details
server.port=2525
#Connection Details(DataSource)
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
# Data Source - CP
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=15
spring.datasource.hikari.pool-name=HikariCP
#Hibernate(JPA) Details
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
SpringRestMySQLApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringRestMySqlApplication.class, args);
Employee.java
package com.example.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="emptab")
@Id
@Column(name="eid")
@Column(name="ename")
@Column(name="esal")
private Double empSal;
public Employee() {
super();
super();
this.empId = empId;
this.empName = empName;
this.empSal = empSal;
return empId;
this.empId = empId;
return empName;
this.empName = empName;
return empSal;
}
this.empSal = empSal;
@Override
EmployeeRepository.java
package com.example.demo.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Employee;
IEmployeeService.java
package com.example.demo.service;
import java.util.List;
import com.example.demo.model.Employee;
package com.example.demo.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.example.demo.model.Employee;
import com.example.demo.repo.EmployeeRepository;
@Service
@Autowired
@Override
return repo.save(emp).getEmpId();
@Override
repo.deleteById(empId);
@Override
Optional<Employee> empOp=repo.findById(empId);
if(empOp.isPresent())
return empOp.get();
else
return null;
@Override
List<Employee> emps=repo.findAll(Sort.by("empId"));
/*Collections.sort(emps,new Comparator<Employee>() {
@Override
return o1.getEmpId()-o2.getEmpId();
});*/
//Collections.sort(emps,(o1,o2)->o1.getEmpId()-o2.getEmpId());
return emps;
@Override
return repo.existsById(empId);
SwaggerConfig.java
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@Bean
.select()
.apis(basePackage("com.example.demo.controller"))
.paths(regex("/rest.*"))
.build()
.apiInfo(apiInfo());
"Snap-1.0", "https://sathyatech.com/",
new Contact(
"RSS",
"http://sathyatech.com",
),
}}
EmployeeRestController.java
package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Employee;
import com.example.demo.service.IEmployeeService;
@RestController
@RequestMapping("/rest/emp")
@Autowired
@PostMapping("/save")
String message=null;
ResponseEntity<String> response=null;
try {
Integer empId=service.saveEmployee(emp);
response=new ResponseEntity<String>(message,HttpStatus.OK);
} catch (Exception e) {
response=new
ResponseEntity<String>(message,HttpStatus.INTERNAL_SERVER_ERROR);
e.printStackTrace();
return response;
@DeleteMapping("/delete/{empId}")
String message=null;
ResponseEntity<String> response=null;
try {
if (empId==null) {
response=new
ResponseEntity<String>(message,HttpStatus.BAD_REQUEST);
}else if(service.isEmployeeExistById(empId)) {
service.deleteEmployee(empId);
response=new ResponseEntity<String>(message,HttpStatus.OK);
}else {
response=new
ResponseEntity<String>(message,HttpStatus.NOT_FOUND);
} catch (Exception e) {
response=new
ResponseEntity<String>(message,HttpStatus.INTERNAL_SERVER_ERROR);
e.printStackTrace();
return response;
@GetMapping("/all")
String message=null;
ResponseEntity<?> response=null;
try {
List<Employee> emps=service.getAllEmployees();
if(emps==null || emps.size()==0) {
response=new
ResponseEntity<String>(message,HttpStatus.NO_CONTENT);
}else {
response=new ResponseEntity<List<Employee>>(emps,HttpStatus.OK);
} catch (Exception e) {
response=new
ResponseEntity<String>(message,HttpStatus.INTERNAL_SERVER_ERROR);
e.printStackTrace();
return response;
}
Build and Deployment Process:
Build: It is a process of converting our java code to final executable format after compiling all java files.
Note:
#3 After development, execute maven goals “maven clean”, “maven build”, ”maven test” (for build
testing). OR all in one “maven install”
Steps:
>make it as default ok
>Right click on project > Build Path>configure build path > Choose JRE System library> Edit > Choose
workspace default> Apply and close.
application.properties:-
server.port=2020
Provider class:
package com.app.provider;
@RestController
@GetMapping(“/show”)
return “Hello”;
*Here @RequestMapping is used to provide common path for all method if we write at class level.
URL:
http://localhost:2020/myapp/rest/emp/show
**To stop server running using cmd prompt use “ctrl+c” *cancel process+
We can run our application in browser or postman
1. H2
2. HSQL
3. Apache Derby
Also support different database like mysql, oracle, postgres, etc. with default connection
pooling “tomcat server connection pooling” also supports 3rd party connection pooling apache
DBCP, Hikary.
Also supports “caching” to reduce round network calls using “EnCache” or 3rd party like
“jCache”, “redis”, etc.
To perform DB operations, use Spring Boot Data JPA API which will write all operations code for
programmer.
**Spring Boot auto generates code for Hibernate configuration, Connection Creation, with pooling,
basic operations code, pagination, specification, sorting HQL’s, Multiplicity, Connection Mapping, etc.
#1 Model Class:
A class mapped with DB table using JPA Annotations [@Entity @Table @Column @Id] is called as
“Model Class or Entity Class”. It follows ORM (Object Relational Mapping)
#1 Create one Spring Boot Project with dependencies web, H2, JPA
>Choose dependencies
Ex:
package com.app.model
@Entity
@Table(name=”emptab”)
@Column(name=”eid”)
@Column(name=”ename”)
@Column(name=”esal”)
//const, p.const
//set get
//toString
package com.app.repo;
#4 Enable JpaRepository in Spring Boot starter class also implements CommandLineRunner run()
method, execute one by one operations.
package com.app;
@SpringBootApplication
@EnableJpaRepositories
SpringApplication.run(SpringDBOperation.class,args);
@Autowired
repo.save(e1);
e1.setEmpName(“JJ”);
repo.save(e1); // update (if we want to update only this then we write Annotation in
model class at class level)
repo.saveAll(emps);
application.properties
server.port=2525
spring.jpa.show-sql=true
Step#1 Create Spring Boot Starter project using web and Jpa dependencies
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
Step#3 Provide Datasource (connection) and JPA (Hibernate) details in application.properties file
--application.properties
#server details
server.port=2525
spring.datasource.driver-class-name=com.mysql.jdbc.driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
Service Layer is used to define Application logic, Transaction Management, Data Sorting, etc.
1. findBy()
2. @Query
#1 findBy():
Spring Boot Data Jpa has provided default methods findById and findAll methods which are used to
fetch data based on Primary key columns only.
To get Data based on non-primary key column define our own method using findBy() syntax, which also
supports conditions and Joins like “and, or, in, isNull”.
These methods must be added in Repository interface as abstract methods, body(logic) will be provided
by Spring Boot Data Jpa only.
package com.app.repo;
This is used to execute on HQL written manually by programer. We can specify customized query here
which stores final result to method return Type.
Long countTotalRowsInEmp();
Double getMaxSalfromEmployees();
1. Pool
2. Cache
#1 Pool:
It is a group of similar objects that is all objects related to one class type.
Connection Pool means group of readymade connection objects which provides faster execution for
database operations. Every Spring Boot application must be configured with one connection pool
concept for database programing.
#1 Hikary CP is a default connection pool used by Spring Boot Data which works faster than other
connection pool.
#2 Tomcat connection pool works only with tomcat server, if server changed then it will not work.
#3 Apache DBCP 2.x is a 3rd party service provided by apache for basic connection pool concept. It is
recommended to use in development environment not in production environment.
#2 Cache:
#2 Provide pool properties like pool size, timeout, maxsize, ideal time, etc.
#4 On performing operations every connection pool object will be called (based on load) and return
back to pool.
a. Read connection from pool
b. Execute operation
c. Return connection back to CP
#5 On server shutdown it will close all connection objects that is pool is closed or shutdown.
Hikary CP setup:
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikaryCP</artifactId>
</dependency>
spring.datasource.hikari.*=
spring.datasource.tomcat.*=
spring.datasource.dbcp2.*=
application.properties:
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikary.minimum-idle=15
spring.datasource.hikari.pool-name=HikariCP
-> Use Autowired for datasource (javax.sql) in any class and print it is reference.
Ex: @Autowired
Sysout(datasource)
Swagger is a 3rd party UI tool. It provides easy UI for testing of provider application. To create this UI we
need to follow below steps:
Step#4 Optional
All above steps must be provided as “SwaggerUI” config class in Spring Boot.
*Also add devTool dependency to perform dev operation like (add swagger dependency)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
Code:
package com.app.config;
@Configuration
@EnableSwagger2
.select()
.apis(basePackage(“com.app.controller”))
.path(regex(“/rest.*”))
.build();
By using Spring WEB MVC and Spring Boot services and Data Jpa with other utility classes like spec,
validator, util, etc.
UI Technologies:
To implement this, we are using layers, loosely coupled model using HAS-A with POJI-POJO.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringWebMvcApp</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringWebMvcApp</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=2626
#ViewResolver Details
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
#Connection Details
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot
spring.datasource.username=root
spring.datasource.password=root
#Hibernate Details
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#Pool Details
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=15
spring.datasource.hikari.pool-name=HikariCP
banner.txt
_____ _ _
/ ___| || ||
\ `--. __ _ | |_ | |__ _ _ __ _
__/ |
|___/
ServletIntializer.java
package com.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringWebMvcAppApplication.class);
SpringWebMvcAppApplication.java
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringWebMvcAppApplication.class, args);
Employee.java
package com.app.model;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="emptab")
@Id
@Column(name="eid")
@GeneratedValue(generator="empgen")
@GenericGenerator(name="empgen",strategy="increment")
@Column(name="ename")
@Column(name="email")
@Column(name="egen")
@Column(name="addr")
@ElementCollection
@CollectionTable(
@Column(name="idType")
@Column(name="idnum")
//alt+shift+S,O(De-select-all>OK)
public Employee() {
super();
super();
this.empId = empId;
public Employee(Integer empId, String empName, String empMail, String empGen, String
empAddr, List<String> empLangs,
super();
this.empId = empId;
this.empName = empName;
this.empMail = empMail;
this.empGen = empGen;
this.empAddr = empAddr;
this.empLangs = empLangs;
this.empIdType = empIdType;
this.empIdNum = empIdNum;
//alt+shift+S,R (selectAll>OK)
return empId;
this.empId = empId;
}
public String getEmpName() {
return empName;
this.empName = empName;
return empMail;
this.empMail = empMail;
return empGen;
this.empGen = empGen;
return empAddr;
this.empAddr = empAddr;
this.empLangs = empLangs;
return empIdType;
this.empIdType = empIdType;
return empIdNum;
this.empIdNum = empIdNum;
//alt+shift+S,S(OK)
@Override
+ empIdNum + "]";
}
}
EmployeeRepository.java
package com.app.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.app.model.Employee;
EmployeeSpec.java
package com.app.spec;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import com.app.model.Employee;
this.filter = filter;
}
@Override
//cb.disjunction() ; //or
p.getExpressions()
.add(
cb.equal(root.get("empId"), filter.getEmpId())
);
p.getExpressions()
.add(
cb.like(root.get("empName").as(String.class),
"%"+filter.getEmpName()+"%")
);
p.getExpressions()
.add(
cb.like(root.get("empMail").as(String.class),
"%"+filter.getEmpMail()+"%")
);
return p;
}
}
EmployeeValidator.java
package com.app.validator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.app.model.Employee;
@Component
@Override
return Employee.class.equals(clazz);
@Override
Employee e=(Employee)target;
if(e.getEmpName()==null || "".equals(e.getEmpName().trim())){
if(StringUtils.isEmpty(e.getEmpMail()) ||
StringUtils.containsWhitespace(e.getEmpMail())) {
}
if(StringUtils.isEmpty(e.getEmpGen()) ||
StringUtils.containsWhitespace(e.getEmpGen())) {
if(StringUtils.isEmpty(e.getEmpAddr()) ||
StringUtils.containsWhitespace(e.getEmpAddr())) {
if(e.getEmpLangs()==null || e.getEmpLangs().isEmpty()) {
if(StringUtils.isEmpty(e.getEmpIdType())) {
if(StringUtils.isEmpty(e.getEmpIdNum()) ||
StringUtils.containsWhitespace(e.getEmpIdNum())) {
IEmployeeService.java
package com.app.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import com.app.model.Employee;
public interface IEmployeeService {
//special methods
EmployeeServiceImpl.java
package com.app.service.impl;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.app.model.Employee;
import com.app.repo.EmployeeRepository;
import com.app.service.IEmployeeService;
@Service
public class EmployeeServiceImpl implements IEmployeeService{
@Autowired
@Override
return repo.save(emp).getEmpId();
@Override
repo.deleteById(empId);
@Override
return repo.existsById(empId);
@Override
Optional<Employee> emp=repo.findById(empId);
if(emp.isPresent())
return emp.get();
else
return null;
@Override
Collections.sort(emps, (e1,e2)->e1.getEmpId()-e2.getEmpId());
return emps;
//special methods
@Override
return repo.findAll(pageable);
@Override
EmployeeController.java
package com.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
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 com.app.model.Employee;
import com.app.service.IEmployeeService;
import com.app.spec.EmployeeSpec;
import com.app.validator.EmployeeValidator;
@Controller
@Autowired
@Autowired
@GetMapping("/reg")
return "EmployeeRegister";
@PostMapping("/insert")
validator.validate(employee, errors);
if(errors.hasErrors()) {
map.addAttribute("employee", employee);
}else {
Integer empId=service.saveEmployee(employee);
//clear form
return "EmployeeRegister";
@GetMapping("/viewAll")
List<Employee> emps=service.getAllEmployees();
map.addAttribute("emps", emps);
return "EmployeeData";
@GetMapping("/viewPage")
public String
showPageData(@PageableDefault(page=0,size=3,sort="empId",direction=Direction.ASC) Pageable
pageable,@ModelAttribute Employee filter ,ModelMap map) {
Page<Employee> emps=service.getAllEmployees(spec,pageable);
map.addAttribute("page", emps);
map.addAttribute("filter", filter);
return "EmployeeData";
@GetMapping("/delete")
service.deleteEmployee(eid);
return "redirect:viewPage";
@GetMapping("/viewOne")
Employee emp=service.getEmployeeById(empId);
map.addAttribute("emp", emp);
return "EmployeeView";
@GetMapping("/edit")
Employee e=service.getEmployeeById(empId);
map.addAttribute("employee", e);
return "EmployeeEdit";
@PostMapping("/update")
public String updateEmp(@ModelAttribute Employee employee) {
service.saveEmployee(employee);
return "redirect:viewPage";
EmployeeRegister.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<h1>Welcome to Employee</h1>
<pre>
<form:errors path="empName"/>
<form:errors path="empMail"/>
<form:errors path="empAddr"/>
<form:errors path="empLangs"/>
ID : <form:select path="empIdType">
<form:option value="">--select--</form:option>
<form:option value="AADHAR">AADHAR</form:option>
<form:option value="OTHER">OTHER</form:option>
</form:select>
<form:errors path="empIdType"/>
<form:errors path="empIdNum"/>
</pre>
</form:form>
${message}
</body>
</html>
EmployeeData.jsp
<html>
<head>
<title>Employee Data</title>
</head>
<body>
<pre>
ID : <form:input path="empId"/>
Email:<form:input path="empMail"/>
</pre>
</form:form>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th colspan="3">OPERATIONS</th>
<!-- <th>GENDER</th>
<th>ADDRESS</th>
<th>LANGUAGES</th>
<th>ID</th>
<th>NUMBER</th> -->
</tr>
<tr>
<td>
<a href="viewOne?empId=${e.empId}">
</a>
</td>
<td>
<a href="delete?empId=${e.empId}">
</a>
</td>
<td>
<a href="viewOne?empId=${e.empId}">
</a>
</td>
<td>
<a href="edit?empId=${e.empId}">
</a>
</td>
</tr>
</c:forEach>
</table>
<c:if test="${page.hasContent()}">
<c:if test="${!page.isFirst()}">
<a href="?page=0">First</a>
</c:if>
<c:if test="${page.hasPrevious()}">
<a href="?page=${page.getNumber()-1}">Previous</a>
</c:if>
<c:choose>
${i+1}
</c:when>
<c:otherwise>
<a href="?page=${i}">${i+1}</a>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${page.hasNext()}">
<a href="?page=${page.getNumber()+1}">Next</a>
</c:if>
<c:if test="${!page.isLast()}">
<a href="?page=${page.getTotalPages()-1}">Last</a>
</c:if>
</c:if>
</body>
</html>
EmployeeView.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<table border="1">
<tr>
<td>ID</td>
<td>${emp.empId}</td>
</tr>
<tr>
<td>NAME</td>
<td>${emp.empName}</td>
</tr>
<tr>
<td>EMAIL</td>
<td>${emp.empMail}</td>
</tr>
<tr>
<td>GENDER</td>
<td>${emp.empGen}</td>
</tr>
<tr>
<td>ADDRESS</td>
<td>${emp.empAddr}</td>
</tr>
<tr>
<td>LANGUAGE</td>
<td>${emp.empLangs}</td>
</tr>
<tr>
<td>ID TYPE</td>
<td>${emp.empIdType}</td>
</tr>
<tr>
<td>ID NUM</td>
<td>${emp.empIdNum}</td>
</tr>
</table>
</body>
</html>
EmployeeEdit.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Edit Page!!</title>
</head>
<body>
<pre>
<form:errors path="empName"/>
<form:errors path="empMail"/>
<form:errors path="empGen"/>
<form:errors path="empAddr"/>
<form:errors path="empLangs"/>
ID : <form:select path="empIdType">
<form:option value="">--select--</form:option>
<form:option value="AADHAR">AADHAR</form:option>
<form:option value="OTHER">OTHER</form:option>
</form:select>
<form:errors path="empIdType"/>
<form:errors path="empIdNum"/>
<input type="submit" value="Update"/>
</pre>
</form:form>
</body>
</html>
If checkbox is used at UI, at a time multiple values can be selected. So primitive variable like String, Long
is not good to use to use to store all values.
Choose List<String> type, every list type will be stored in a child based on Hibernate Design with 3
columns (key, element, index)
Code:
@ElementCollection keyColumn
@CollectionTable(name=”emptab”, joinColumns=@JoinColumns(name=“eid”))
1. ModelAttribute: It is used to fetch form data in the object format. On click submit button, complete
Spring Form completed to model Class object. Object be given by programmer at form tag level
using <form:form… modelAttribute=”employee”>
2. To read this data at controller @ModelAttribute Employee employee
3. ModelMap: It is use to send data from controller to UI. Use method “addAttribute(key,value)” to
add data to ModelMap, use same key at UI level to read data.
package com.app.controller;
@Controller
@Autowired
@GetMapping (“/reg”)
return “EmployeeRegister”;
return “EmployeeRegister”;
}
}
All errors checking must be done in validate() method. Here target means model class object.
Validator class must be used in controller with HAS-A relation show below:
Note:
<form:errors path=”*”/> OR
<form:errors path=”variableName”>
@PostMapping (“/insert”)
public String saveEmp (@ModelAttribute Employee employee, Errors errors, ModelMap map) {
//1. Do validate
validator.validate(employee,errors);
if(errors.hasErrors()){
map.addAttribute(“employee”,employee);
} else {
//3. If no errors
//clear form
map.addAttribute(“employee”,new Employee());
return EmployeeRegister;
}
Webservice
MediaType Annotations:
@Consumes and @Produces are known as MediaType annotation those are used to convert JSON/XML
(Global Format Data) to Object and Object to Global Format (JSON/XML).
@Consumes: It will converts Global Data taken from and converts into Object format, This object is
given as input to method (as parameter)
@Produces: It converts object which is method return value (output) and placed into HttpResponse
Body.
@Produces (“application/json”)
This JSON Data will be converted to Product class object and given as input to show ()
show() executes method body by taking product object as input and returns finally model class object.
Model class object will be converted to JSON and placed into HttpResponseBody
MediaType is a class given from javax.ws.rs.core package and APPLICATION_JSON is a static property
which has internal value=”application/json”
@Consumes (“application/xml”) is equal to @Consumes(MediaType.APPLICATION_XML)
Every class object can be converted to JSON, even JSON can be converted to any class object.
Every class object cannot be converted to xml format. Only JAXB (Java Architecture for XML Binding)
class object can be converted to xml.
#1 Define one method in EmployeeController which will be executed for URL request “/viewAll”, It
should be get data from DB using service layer and send to UI.
@GetMapping (“/viewAll”)
map.addAttribute(“emps”,emps);
return “EmployeeData”;
<c:out value=”$,e.empId-”/>
<c:out value=”$,e.empName-”/>
<c:out value=”$,e.empSal-”/>
</c:forEach>
</html>
Spring Data JPA has provided interface pagination “PagingAndSortingRepository” for pagination with
Data sorting process.
Pageable = Input for pagination like page Number, size of page, sort type.
Page = Output of pagination like page data, next, previous, last, first.
http://....viewPage?page=3&size=2&sort=empName
Note:
#1 If number of pages are 10 (ex) then page number starts from zero (0) and ends by size-1 i.e. 9
#2 isFirst() and isLast() boolean methods are used to identify current page is firstPage (zero) and
lastPage (size-1)
#3 It support hasPrevious() and hasNext() for navigation to next and previous pages.
#4 To provide default pagination details use annotation: @PageableDefault with details like: page=0,
size=3, sort=”empId”, direction=DirectionAs.
**boolean hasContent();
#2 Model class
package com.app;
//set-get, const
//toString()
#3 Provider class
package com.app;
@Path (“/msg”)
@GET
@Path (“/msg”)
@Produces (“application/JSON”)
e.setEmpId (10);
e.setEmpName (“AA”);
e.setEmpSal (“2.2”);
return e;
#4 Consumer Code
package com.app;
public class Test {
Sysout (str);
Sysout (cr.getStatus());
Sysout (cr.getType());
Output:
200
Ok
{},
{},
{}
package com.app;
@Path (“/msg”)
@GET
@Path
@Produces (MediaType.APPLICATION_JSON)
return emp;
}
[{
“empId”:10,
“empName”:”A”,
“empSal”:2.1
},
“empId”:11,
“empName”:”B”,
“empSal”:2.1
},
“empId”:12,
“empName”:”B”,
“empSal”:2.1
**)Override equals() and hascode() methods in case of collection type set<Employee > or it’s equal
//alt+shift+s,h (ok)
package com.app;
// ctrl+shift+O(imports)
@XMLRootElement
public class Employee{
//set,get………to String
#2 Provider class
package com.app;
@Path (“/msg”)
@GET
@Path
@Produces (MediaType.APPLICATION_XML)
emp.setEmpId (10);
emp.setEmpName (“AA”);
emp.setEmpSal (“2.3”);
return emp;
O/p: <Employee>
<empId>10</empId>
<empName>AA</empName>
<empSal>2.3</empSal>
</Employee>
Specification API for Spring Boot Data JPA:
It is used to design one predicate with select for data fetching based on dynamic input given by end
user. (Generating sql queries at runtime)
Here, Predicate indicates “where clause creation with conditional gives like and/or”.
In case of search/filter screen concepts by default, we should use JpaSpecification Executor <I>.
Method:
Coding Steps:
#1 Enable process for module using repository interface that extends JpaSpecificationExecutor<T>
#2 Define Specification class that generates predicate based on input CriteriaBuilder, CriteriaQuery,
Root.
#4 Design Filter Screen/Search Screen using HTML form/Spring form Tag library with type GET (not POST
type here).
#5 on click “Search” button form converted to model class object (filter) object
#7 Send Page<T> to UI back to display data also and filter object to ModelMap.
Example:
(and condition) Conjunction = select * from employee where empId=? and empName=?
#1 EmployeeRepository (I) must extends One Predefined interface JpaSpecificationExecutor<T> (I) to use
method findAll(Specification,Pageable):Page
#2 Define one class for Specification process which must implements Specification(I) given by Spring
Boot Data Jpa.
#4 All logic to expression if filter variable is not empty && not null
#5 Add one method in IEmployeeService which gets Pagination Data ‘Page<T>’ by taking inputs like
Spec, Pageable.
#11 Define search form with ‘GET’ type with ModelAttribute =’filter’ at EmployeeData.jsp
https://devops.datenkollektiv.de/banner.txt/index.html
It is a process of constructing url using static path & Dynamic path, by using anchor tag <a> and
ExpressionLanguage (EL).
In Data.jsp add below code under <forEach> before closing <tr> tag.
<td>
<a href=”delete?empId=$,e.empId-”>Delete</a>
</td>
behave as respose.sendRedirect(url)
**If module has multiple fields to display data, we must create viewPage to show all values in search
page show only few important fields.
**Also create Hyperlink “view” at every row using URL-Writing like below:
<a href=”viewOne?empId=$,e.empId-”>View</a>
**In Controller class, define one method to fetch data based on empId and send same data to
EmployeeView page to display it.
Example:
Data Edit Operation in Spring Boot:
#1 create one Hyperlink ie <a> tag in Data Jsp Page Using URL-ReWriting.
Code:-
<a href=”edit?empId=$,e.empId-”>EDIT</a>
http:--------/edit?empId=20
Here
#3.Define one JSP named as “EmployeeEdit” with Spring from tag library .we can
On click submit(update) button form data will be converted to Object is called as ModelAttribute.
#4 On click submit (update) button form Data will be converted to Object i.e. called as ModelAttribute.
#5 Read ModelAttribute at controller method and call service, saveEmployee (emp) redirect to viewPage
to come back “EmployeeData” Jsp with new Data.
Execution Flow Design:
#1 In application.properties file configure host, port, username and password with extra secure
properties like auth, startls.enable [tls - > Transport Layer Security]
#3 JavaMailSender (I) is an interface, for this JavaMailSenderImpl (C) class object will be auto created by
Spring Boot.
Example: SpringBootEmail
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringBootEmail</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringBootEmail</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#Server Config
server.port=2626
# Email config
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.password=2019javaraghu2019
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
ServletInitializer.java
package com.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringBootEmailApplication.class);
}
SpringBootEmailApplication.java
package com.app;
import java.io.File;
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.core.io.FileSystemResource;
import com.app.email.EmailUtil;
@SpringBootApplication
SpringApplication.run(SpringBootEmailApplication.class, args);
@Autowired
@Override
System.out.println(issent);
System.exit(0);
}
EmailUtil.java
package com.app.email;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
@Component
@Autowired
boolean sent=false;
try {
MimeMessage message=mailsender.createMimeMessage();
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
helper.setFrom("[email protected]");
if(file!=null)
helper.addAttachment(file.getFilename(), file);
mailsender.send(message);
sent=true;
} catch (Exception e) {
sent=false;
e.printStackTrace();
return sent;
YML:
It provides chain method for writing of key=value, also called as Human Readable Format.
Use symbol “:” with tab space for next level of key.
Example:
server:
port:2200
spring:
mvc:
view:
prefix:/WEB-INF/views/
suffix:.jsp
datasource:
driver-class-name:com.mysql.jdbc.driver
url:jdbc:mysql://localhost:3306/boot
username:root
password:root
hikari:
connection-timeout:1000
maximum-pool-size:20
minimum-idle:15
pool-name:HikariCP
jpa:
show-sql:true
hibernate:
ddl-auto:update
Security in SpringBoot:
Authorized: Here both Login and Role required to access URL. Role also called as Authority.
Types of Authentication:
1. InMemoryAuthentication (RAM)
2. JdbcAuthentication (JDBC)
3. UserDetailService (ORM)
1. InMemoryAuthentication: It is used to store details in RAM. Details like Username, Password and
Role.
To implement this concept we must define one class that extends WebSecurityConfigurerAdapter and
must apply annotation @EnableWebSecurity.
Code:
package com.app.config;
@Configuration
@EnableWebSecurity
//un,pwd,role
@Autowired
//url levels
@override
CacheManager(I) is used to manage cache concept for 2nd level SessionFactory cache in boot
applications, which reduces network calls between application and Database. So this improves the
performance.
Steps to implement cache Management in Spring Boot Application:
#1 Enable Cache Concept in Application by adding below annotation over starter class level
@EnableCaching
#2 Define Cache manager impl class which manages Second Level Cache (Session Factory Cache)
ConcurrentMapCacheManager(C)
@Cacheable: It must be applied over method which will select one row (ex: findById), Also works for all
rows select but not recommended.
@CacheEvict: It must be applied over delete operations, it will remove data from II-Level cache Map.
@CachePut: It must be applied over update operation, which updates data in cache (II-level) when
update() operation is done.
*) Below code creates one Map in II-Level cache with Map name as “employee”
@Bean
return cm;
}
*) To place data in employee map code looks like
@CachePut(value=”employee”)
@CacheEvict(value=”employee”)
@Cacheable (value=”employee”)
*) Profiles handles
>application.properties
*) We will be having different profiles like Production, QA, DEV, Cloud, UAT, PS, etc. Database Details,
Pooling, Logging, Security may get changes from one profile to another.
*) In this case we should not modify existed application.properties, we should define new properties file
with profile name.
*) Profiles are used to execute logic selected for environment.
*) Here, default implementation is given by ProductServiceImpl, it will do save work. It is also called as
“default Profile”.
*) for Customer DHL, it should work as email & save, then define another Impl as
DhlProdcutionServiceImpl as profile “dhl”.
*) for Customer E-Trans, it should work as print and save, then define another impl as
EtransProductionImpl as profile “etrans”.
application-[profileName].properties
#3 Selection and Execution of Profile System Arguments (VM Arguments) cmd line arguments
spring.profile.active property
#2 VM/System Arguments:
It creates variable with data at JVM level, so that it can be accessed in any application running in same
JVM, using code
Example:
Sysout(“ID:”+args*0+);
Sysout(“Name:”+args*1+);
String s = System.getProperty(“data”);
Default
#2 for every customer and any environment default profile will be activated by springBoot, which reads
Properties from application.properties file.
#3 For DHL customers, logic should work in different way not in default way then we are writing another
implementation class which is annotated with “@Profile(“dhl”)”, in a same way for Etrans customer we
should write another implementation annotated with “@Profile(“etrans”)”.
#4 In case of DHL Profile it will search for application-dhl.properties file, if not found it will read data
from default file application.properties.
--spring.profiles.active=dhl
-Dspring.profiles.active=dhl
spring.profiles.active=dhl
Example: SpringBootProfilesEx
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringBootProfilesEx</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringBootProfilesEx</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=2626
#spring.profiles.active=etrans-prof
application-dml-prof.properties
application-etrans-prof.properties
ServletInitializer.java
package com.sathyatech.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringBootProfilesExApplication.class);
}
SpringBootProfilesExApplication.java
package com.sathyatech.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.sathyatech.app.service.IEmployeeService;
@SpringBootApplication
SpringApplication.run(SpringBootProfilesExApplication.class, args);
@Autowired
@Override
System.out.println(service.getMessage());
System.exit(0);
IEmployeeService.java
package com.sathyatech.app.service;
EmployeeServiceImpl.java
package com.sathyatech.app.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("default")
@Value("${myapp.message}")
@Override
DHLEmployeeServiceImpl.java
package com.sathyatech.app.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("dml-prof")
@Value("${myapp.message}")
@Override
EtransEmployeeServiceImpl.java
package com.sathyatech.app.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Service
@Profile("etrans-prof")
@Value("${myapp.message}")
@Override
To execute one task in application automatically (without any manual request or input provided by end
user) based on point of time (exact Date or Time or Both) , Period of Time (
days/weeks/months/hours/minutes/sec) gap (not exact date and time).
1) After 45 days
2) For every 2 minutes
3) With 15 minute gap
4) After 4 hours 10 minutes 3 seconds
Note:
#1 These are used to execute regular work in application like Generate Report on end of
day/month/year.
Syntax: ${cronExpression}
#5 Every Scheduler will be executed automatically, no request should be made by end user.
#8 Period of Time can be provided using fixedDelay/fixedRate and even cron expression.
Example Application:
#Step1 Enable Scheduling concept in application using annotation @EnableScheduling at starter class
level.
#Step2 Define one Service/Component class with void method (write any logic)
@Component
Class Process{
@Scheduled(fixedDelay=4000)
Sysout(“Hi..:”+new Date());
fixedDelay will execute doWork(m1) will be executed with every 4 sec gap on last finish of method.
@Scheduled(fixedRate=2000)
Sysout(“Hii..”+new Date());
In this case, Scheduler wait for given gap or until last method finish work.
Case#1
Case#2
fixedRate and fixedDelay both works based on Period of time not based on point of time. To specify task
based on Point of Time use Cron expression.
Ex:
Sysout(“Hi:”+new Date());
Cron syntax:
, = possible values
- = range
* = not provided
*/ = point of time/day
Cron = “0 0 8,18 * * *”
Cron = “0 35 13 * * *”
Cron = “0 35 16 12 1”
Ex#5
Cron = “10 2 8 * * *”
8:02:10 AM
Ex#6
Cron = “*/10 2 8 * * *”
8:02:00 > 8:02:10 > 8:02:20 > 8:02:30 > 8:02:40 > 8:02:50
Ex#7
Cron = “25/10 2 8 * * * ”
Ex#8
Jan 8:00:00 AM
Cron = “0 0 8 ? 1 ?”
Example: SpringBootSchedulers
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringBootSchedulers</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>SpringBootSchedulers</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=2626
ServletInitializer.java
package com.sathyatech.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringBootSchedulersApplication.class);
SpringBootSchedulersApplication.java
package com.sathyatech.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
SpringApplication.run(SpringBootSchedulersApplication.class, args);
MyProcess.java
package com.sathyatech.app;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
//@Scheduled(initialDelay=5000,fixedDelay=2000)
//@Scheduled(initialDelay=5000,fixedDelay=2000)
@Scheduled(cron="12,35,55 * * * * *")
System.out.println("Start:"+count);
System.out.println(new Date()+":Hello"+count);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(new Date()+":Hello"+count);
System.out.println("end:"+count);
count++;
It is used to send and receive messages in text, Object and Collection format between two Java
Applications by using middleware MOM (Message Oriented Middleware) ex: Apache Active MQ.
1. Queue
2. Topic
#1 In Peer-To-Peer (P2P) communication Queue Concept is used, which sends message to one
Consumer at a time.
a) ConnectionFactory Creation
b) Connection Creation
c) Session Creation
d) Client Creation
e) Destination
f) Message Creation and Send/Receive
Spring Boot Actuator:
*) Production Environment: - Once application is developed then it is given to end customer using one
server deployment using one server deployment (Deployment=place war in server and start it) with
supportive tools like Logging, Tracing, Health check, Server status, DB Configuration, Current Profile,
Memory Details, etc.
*) Actuator is a service developed using Spring Boot ReST and Spring Boot Security which provides
default setup for Production.
*) This setup can be accessed using URL’s (Endpoints) which is also called as “Production Ready
Environment”.
https://docs.springframework.io/spring-boot/docs/current/reference/html/production-ready-
endpoint.html
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
#3 It should also have Security Dependency added in pom.xml because Spring Boot Actuator is built on
top of Spring Boot Security and Spring Boot ReST web services.
#4 Write app logic for DB operations /Email/ ReST Application/ Security (anything).
#5 Start application (Run starter class) and enter the URL, looks like
https://localhost:2828/actuator/health
#6 In case of older version use direct end points (SpringBoot 1.5.x). In case of new version use endpoint
starts with /actuator (spring Boot 2.x).
1.5.x
http://localhost:2828/beans
2.x
http://localhost:2828/actuator/beans
#7 In Spring Boot 1.5.x,all are enable by default, in 2.x those are in disabled to activate them add one
property in application.properties file
management.endpoint.web.exposure.include=*
#8 Endpoints:
a. /actuator/auditevents: It will audit (notedown) all loggIn operations from different networks
(success/failure logins).
b. /actuator/beans: It will show objects and their dependencies created in container.
c. /actuator/configprops: It will display all properties and system properties loaded by spring boot.
d. /actuator/env: It will show details of JRE, JDK, Version, Server, Jar files etc. details
e. /actuator/health: It will show current status of server and App possible values [UP/DOWN].
f. /actuator/httptrace: It will show what http request made so far are: ex: /emp/reg, /emp/delete.
g. /actuator/loggers: It will display default logging file provided by SpringBoot
h. /actuator/metrics: Calculations of memory/cache values as map properties shown here.
i. /actuator/mappings: It provides “what url for what method” is provided
j. /actuator/scheduledtask: It will display Scheduler details in App.
Example: Spring5JMSProvider
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>Spring5JMSProvider</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>5.15.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
AppConfig.java
package org.sathyatech.app.config;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
@Configuration
@Bean
cf.setBrokerURL("tcp://localhost:61616");
return cf;
@Bean
return jt;
SendMessageTest.java
package org.sathyatech.app.test;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.sathyatech.app.config.AppConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
AnnotationConfigApplicationContext c=new
AnnotationConfigApplicationContext(AppConfig.class);
JmsTemplate jt=c.getBean(JmsTemplate.class);
@Override
});c.close();}}
Example: Spring5JMSConsumer
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>Spring5JMSConsumer</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
AppConfig.java
package org.sathyatech.app.config;
import javax.jms.ConnectionFactory;
import javax.jms.MessageListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.listener.MessageListenerContainer;
@Configuration
@ComponentScan(basePackages= {"org.sathyatech.app"})
@EnableJms
@Autowired
@Bean
c.setBrokerURL("tcp://localhost:61616");
return c;
@Bean
m.setDestinationName("my-test-spring");
m.setMessageListener(messageListener);
return m;
MyMessegeListner.java
package org.sathyatech.app.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import org.springframework.stereotype.Component;
@Component
@Override
try {
System.out.println(tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
Test.java
package org.sathyatech.app.test;
import org.sathyatech.app.config.AppConfig;
import org.sathyatech.app.listener.MyMessageListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
AnnotationConfigApplicationContext ac=new
AnnotationConfigApplicationContext(AppConfig.class);
MyMessageListener ms=ac.getBean(MyMessageListener.class);
}
Spring Boot Log4j Example using Slf4j API:
#2 It provides default Layout and Appender for both Console and File System.
#3 Programmer has to add Logger object in class level and specify LOG LEVEL in application.properties.
--Code—
application.properties:
logging.level.com.app=DEBUG
logging.level.org.springframework=OFF
logging.level.org.hibernate=OFF
logging.file=myapp.log
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
..
http://localhost:2828/actautor/logfile
It means request and response are executed in circular chain manner i.e. (one by one).
AJAX stands for “Asynchronous Javascript And XML”, it means application into Asynchronous mode, that
means to make new request, client not required to wait for previous response.
AJAX calls are controlled using Events made by inputs (Keyboard, mouse, form inputs,).
Every Input can be connected to AJAX call using events only. This even will be automatically triggered by
input component, programer not required to make even call externally.
Ajax makes request based on even and gets response back from server.
Syntax:
AJAX Coding Steps:
#1 Define JSP/HTML page with simple text input with name and id properties.
HTML Form:
--OR—
Spring Form:
<form:input path=”empName”>
#2 Add Script Line to enable JQuery with its library in JSP/HTML, Head Area
#3 Define JQuery code for Ajax call based on empName-> change event
<script type=”text/javascript”>
$(document).ready(function(){
$(“#empName”).change(function(){
$.ajax({
url:’getData’,
data:{“empName”:$(“#empName”).val()},
success:function(resTxt){
$(“#resultArea”).text(resTxt);
}
});
});
});
@Controller
@GetMapping(“/getData”)
}}
Example: SpringBootJQueryAjaxExample
pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>SpringBootJQueryAjaxExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringBootJQueryAjaxExample</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=2626
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
ServletInitilizer.java
package com.example.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@Override
return application.sources(SpringBootJQueryAjaxExampleApplication.class);
HomeController.java
package com.example.app;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@GetMapping("/home")
return "Home";
@GetMapping("/getData")
System.out.println(name);
SpringBootJQueryAjaxExampleApplication.java
package com.example.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(SpringBootJQueryAjaxExampleApplication.class, args);
}
Home.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#empName").change(function(){
$.ajax({
url:'getData',
data:{"empName":$("#empName").val()},
success:function(resTxt){
$("#resultBox").text(resTxt);
});
});
});
</script>
</head>
<body>
</body>
</html>
Annotations:
@SpringBootApplication:
#1 @ComponentScan: It must provided by programer in case of Spring applications but in Spring Boot it
will be auto selected based on Starter class.
So we should create all classes under sub or current package of base package.
EX: Add starter-data-jpa in pom.xml then Spring Boot will create <bean> s for