20 Spring Boot
20 Spring Boot
Spring Boot
Spring Boot: Spring Boot makes it easy to quickly bootstrap and start
developing a Spring-based application. It avoids a lot of boilerplate code.
It hides a lot of complexity behind the scene so that the developer can
quickly get started and develop Spring-based applications easily.
Spring MVC: Spring MVC is a Web MVC Framework for building web
applications. It contains a lot of configuration files for various capabilities.
It is an HTTP oriented web application development framework.
Presentation Layer
Business Layer
Persistence Layer
Database Layer
With the help of Spring Initializr, we can easily generate the structure of
the Spring Boot Project.
@SpringBootApplication
public class SbHelloWorldApplication {
package com.wipro.pack;
import org.springframework.web.bind.annotation.RequestMapping;
import import org.springframework.stereotype.Controller;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String sayHello() {
return "Hello World";
}
}
Dependency Injection
4 Autowiring
Simply put, this allows for loose coupling of components and moves the
responsibility of managing components onto the container.
This single instance is stored in the cache and all the subsequent requests
for that named bean return the cached instance.
Even if there is no request raised for a bean object also it will create one
instance for the particular bean class.
If the scope is set to prototype, the Spring Container creates a new bean
instance of the object every time a request for that specific bean is made.
The spring container will create an instance for a particular bean class if
the request is raised. Other wise no instance will be created for the
particular bean class.
@Component @Component
Class Department Class HardDisk
@Component @Component
Class Project Class Battery
@RequestMapping("/home")
public String home() {
return "Home.jsp";
}
}
In case, If I want to store all my view pages in a separate folder and I want
change the view page extension based on customer requirement with out
touching my Controller then the properties file will come to the picture.
@RequestMapping("/home")
public String home() {
return "Home";
}
}
<body>
<form action="AddEmployee">
Employee Id <input type="text" name="eid"/><br>
Employee Name <input type="text" name="ename"/><br>
Employee Salary <input type="text" name="esalary"/><br>
<input type="Submit" value="Add Employee"/>
</form>
</body>
<body>
<form action="AddEmployee">
Employee Id <input type="text" name="eid"/><br>
Employee Name <input type="text" name="ename"/><br>
Employee Salary <input type="text" name="esalary"/><br>
<input type="Submit" value="Add Employee"/>
</form>
</body>
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15
Spring Boot MVC JPA H2.
Now we will create a “EmployeeDao” interface like below.
package com.wipro.pack.dao;
import org.springframework.data.repository.CrudRepository;
import com.wipro.pack.model.Employee;
Now will see the solution for this scenario in the next slide.
Same way, you can have your own deleteBy or removeBy method.
void deleteByEname(String name);
Will see the solution for this scenario in the next slide.
The provider presents the interface and implementation of the service, and
the requester uses the Web service.
REST is used to build Web services that are lightweight, maintainable, and
scalable in nature.
A service which is built on the REST architecture is called a RESTful
service.
The underlying protocol for REST is HTTP, which is the basic web
protocol.
REST stands for REpresentational State Transfer.
REST uses various representation to represent a resource like text, JSON,
XML.
Media types allow an API to inform the client how to interpret the data in
the payload.
Examples:
MediaType.TEXT_HTML
MediaType.TEXT_PLAIN
MediaType.TEXT_XML
MediaType.APPLICATION_JSON
If we perform a GET request, the server looks for the data we requested
and sends it back to us.
package com.wipro.pack.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int eid;
private String ename;
private int esalary;
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename="
+ ename + ", esalary=" + esalary + "]";
}
}
import org.springframework.data.repository.CrudRepository;
import com.wipro.pack.model.Employee;
@Autowired
EmployeeDao dao;
@GetMapping("/getEmployees")
@GetMapping("/getEmployee/{eid}")
public Optional<Employee> getEmployee(@PathVariable("eid") Integer eid) {
return dao.findById(eid);
}
}
package com.wipro.pack.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.wipro.pack.model.Employee;
Postman is a popular API client that makes it easy for developers to create,
share, test and document APIs.
This is done by allowing users to create and save simple and complex
HTTP/s requests, as well as read their responses.
https://www.postman.com/downloads/
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 25
REST GET Method – Example.
@Autowired
EmployeeDao dao;
package com.wipro.pack.dao;
@GetMapping("/getEmployees")
import
public List<Employee> getEmployees() {
org.springframework.data.jpa.repository.JpaRepository;
return dao.findAll();
}
import com.wipro.pack.model.Employee;
@GetMapping("/getEmployee/{eid}")
public interface EmployeeDao extends JpaRepository<Employee,
public Optional<Employee>
Integer>{
getEmployee(@PathVariable("eid") Integer eid) {
return dao.findById(eid);
}
}
@PostMapping("/createEmployee")
public Employee createEmployee(Employee emp) {
return dao.save(emp);
}
@Autowired
EmployeeDao dao;
package com.wipro.pack.dao;
@GetMapping("/getEmployees")
public List<Employee> getEmployees() {
return dao.findAll();
import
}
org.springframework.data.jpa.repository.JpaRepository;
@GetMapping("/getEmployee/{eid}")
import com.wipro.pack.model.Employee;
public Optional<Employee>
getEmployee(@PathVariable("eid") Integer eid) {
public interface EmployeeDao extends JpaRepository<Employee,
return dao.findById(eid);
Integer>{
}
@PostMapping("/createEmployee") }
public Employee createEmployee(Employee emp) {
return dao.save(emp);
}
@PutMapping("/updateEmployee")
public Employee updateEmployee(Employee emp) {
return dao.save(emp);
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 35
REST Put Method – Example.
1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
Note: You can create using STS or Eclipse
2. Create a Department class with required attributes
3. Enable H2 database in properties file
4. Run your application and check database connection – you’ll notice that no tables are available
5. Annotate the Department class with @Entity and the primary key field with @Id
6. Create the DepartmentDAO interface which extends from CRUDRepository
7. Create the DepartmentService Interface
8. Create the DepartmentServiceImpl class and provide Implementation
9. Create the DepartmentController class and required methods
10. Add Tomcat Jasper Dependency in pom.xml
11. Create view pages and test your application
1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
package com.wipro.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
server.port=8123
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:sample
<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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.37</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional> </dependency>
5. Run your application and check database connection – you’ll notice that no tables are available
Once the application has started, Goto to browser and give
http://localhost:8123/h2-console
package com.wipro.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptno;
private String dname;
private String loc;
private double budget;
public Department() {
}
public Department(int deptno, String dname, String loc, double budget) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.budget = budget;
}
public int getDeptno() {
return deptno;
}
Now once you save the changes devtools automatically restarts the server now again connect to H2 and
you can find the Department table
7. Create the DepartmentDAO interface under the package com.wipro.dao which extends from
CRUDRepository
package com.wipro.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
Here we don’t need to implement the DepartmentDao interface and SpringBoot gives us
internal implementation through CrudRepository.
package com.wipro.service;
import java.util.List;
import com.wipro.bean.Department;
package com.wipro.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wipro.bean.Department;
import com.wipro.dao.DepartmentDAO;
/**
*Only insert and show All is implemented
*You are expected to write and test the codes of other operations
@Service
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
DepartmentDAO dao;
@Override
public Department save(Department d) {
return dao.save(d);
}
@Override
public Department findById(Integer id) {
// TODO Auto-generated method stub
return dao.findById(id).get();
}
@Override
public List<Department> findAll() {
List<Department> list = new ArrayList<Department>();
dao.findAll().forEach(dept->list.add(dept));
return list;
}
@Override
public void deleteById(Integer id) {
dao.deleteById(id);
}
@Override
public Department update(Department d) {
return dao.save(d);
}
package com.wipro.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DepartmentController {
@Autowired
DepartmentService service;
@RequestMapping("/menu")
public String showMenu(Model m) {
m.addAttribute("list", service.findAll());
return "Menu";
}
@RequestMapping("/insertForm")
public String showInsertForm(Model m) {
m.addAttribute("dept", new Department());
return "InsertForm";
}
@RequestMapping("/saveForm")
public String saveForm(@ModelAttribute("dept") Department dept, Model m) {
service.save(dept);
m.addAttribute("msg", "Inserted/Updated Successfully");
m.addAttribute("list", service.findAll());
return "Menu";
}
@RequestMapping("/showAll")
public String showAll(Model m) {
m.addAttribute("list", service.findAll());
return "ShowAll";
}
Menu.jsp Page
<br/>
${msg }
<center>
<h2>Menu Items</h2>
<a href="/insertForm" class="btn btn-primary">Insert an Departments</a>
<a href="/showForm" class="btn btn-primary">Show an Departments</a>
<a href="/updateForm" class="btn btn-primary">Update an Departments</a>
<a href="/deleteForm" class="btn btn-primary">Delete an Departments</a>
<a href="/showAll" class="btn btn-primary">Show All Departments</a> <br/><br/>
</center>
<c:if test = "${list.size()> 0}">
<center><h2>Department List</h2></center>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>Budget</th>
</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
<td>${dep.loc}</td>
<td>${dep.budget}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
InsertForm.jsp Page
ShowAll.jsp
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<h2>Department List</h2>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Output:
Click on insert
1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
Note: You can create using STS or Eclipse
2. Create a Department class with required attributes and Annotate the Department class with
@Entity and the primary key field with @Id
3. Enable H2 database in properties file
4. Create the DepartmentDAO interface which extends from CRUDRepository
5. Create the DepartmentService Interface
6. Create the DepartmentServiceImpl class and provide Implementation
7. Create the DepartmentController class and required methods
8. Create view pages and test your application
1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
package com.wipro.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptno;
private String dname;
private String loc;
private double budget;
public Department() {
}
public Department(int deptno, String dname, String loc, double budget) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.budget = budget;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
server.port=8123
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:sample
<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>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.37</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional> </dependency>
5. Run your application and check database connection – you’ll notice that no tables are available
Once the application has started, Goto to browser and give
http://localhost:8123/h2-console
6. Create the DepartmentDAO interface under the package com.wipro.dao which extends from
CRUDRepository
package com.wipro.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
package com.wipro.service;
import java.util.List;
import com.wipro.bean.Department;
package com.wipro.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wipro.bean.Department;
import com.wipro.dao.DepartmentDAO;
@Autowired
DepartmentDAO dao;
@Override
public Department save(Department d) {
return dao.save(d);
}
@Override
public List<Department> findAll() {
List<Department> list = new ArrayList<Department>();
dao.findAll().forEach(dept->list.add(dept));
return list;
}
@Override
public List<Department> getByDname(String dname) {
return dao.getByDname(dname);
}
@Override
public boolean deleteByDname(String dname) {
dao.deleteByDname(dname);
return true;
@Override
public List<Department> findByBudgetGreaterThan(double budget) {
return dao.findByBudgetGreaterThan(budget);
}
@Override
public List<Department> findByDname(){
return dao.findByDname();
}
}
package com.wipro.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.wipro.bean.Department;
import com.wipro.service.DepartmentService;
@Controller
public class DepartmentController {
@Autowired
DepartmentService service;
@RequestMapping("/menu")
public String showMenu(Model m)
{
m.addAttribute("list",service.findAll());
return "Menu";
}
@RequestMapping("/insertForm")
public String showInsertForm(Model m)
{
m.addAttribute("dept", new Department());
return "InsertForm";
}
@RequestMapping("/saveForm")
public String saveForm(@ModelAttribute ("dept") Department dept,Model m)
{
service.save(dept);
m.addAttribute("list",service.findAll());
return "Menu";
}
@RequestMapping("/showByName")
public String showByNamePage() {
return "ShowByName";
}
@RequestMapping("/byname")
public String showByName(@RequestParam("txtDname") String dname, Model m) {
m.addAttribute("list",service.getByDname(dname));
return "ShowByName";
}
@RequestMapping("/deletebyname1")
public String deletByName(@RequestParam("txtDname") String dname,Model m) {
if(service.deleteByDname(dname))
m.addAttribute("msg", "Deleted Successfully");
else
m.addAttribute("msg", "Delete UnSuccessfull");
m.addAttribute("list",service.findAll());
return "Menu";
}
@RequestMapping("/getBudget")
public String getBudget() {
return "ShowByBudget";
}
@RequestMapping("/showByBudget")
public String showByBudget(@RequestParam("txtBudget") double budget,Model m) {
m.addAttribute("list",service.findByBudgetGreaterThan(budget));
return "Menu";
}
@RequestMapping("/orderedList")
public String orderList(Model m) {
m.addAttribute("list",service.findByDname());
return "Menu";
}
}
Menu.jsp Page
<br/>
${msg }
<center>
<h2>Menu Items</h2>
<a href="/insertForm" class="btn btn-primary">Insert an Departments</a>
<a href="/showByName" class="btn btn-primary">Show By Name</a>
<a href="/deleteByName" class="btn btn-primary">Delete By Name</a>
<a href="/orderedList" class="btn btn-primary">Order By Budget</a>
<a href="/getBudget" class="btn btn-primary">Show By Budget</a><br/><br/>
</center>
<c:if test = "${list.size()> 0}">
<center><h2>Department List</h2></center>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>Budget</th>
</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
<td>${dep.loc}</td>
<td>${dep.budget}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
InsertForm.jsp Page
ShowByName.jsp
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="byname">
Enter Department Name : <input type="text" name="txtDname"/>
<input type="submit">
</form>
<h2>Department List</h2>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>budget</th>
</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
DeleteByName.jsp
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="deletebyname1">
Enter Department Name : <input type="text" name="txtDname"/>
<input type="submit">
</form>
</body>
</html>
ShowByBudget.jsp
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="showByBudget">
Enter Department Name : <input type="text" name="txtBudget"/>
<input type="submit">
</form>
Output:
Click on insert