0% found this document useful (0 votes)
277 views

Spring Boot and MicroServices

ddddddddddddddddddddddd

Uploaded by

Abhishek ojha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
277 views

Spring Boot and MicroServices

ddddddddddddddddddddddd

Uploaded by

Abhishek ojha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

08-SBMS

19-02-2021
Pre-Requisites:-
Core Java
Adv Java(jdbc, servlet & jsp)
SQL (Curd Operations)
ORM Basics
Course content:-
We are dividing into 5 parts
1. Spring Boot Internal
2. Spring Data JPA
3. Spring Web MVC Architecture
4. Restful Services
5. MicroServices
Part 1:- Spring Boot Internals
1. What is Spring Framework
2. Spring Vs Spring Boot
3. Advantages of Spring Boot
4. SpringBoot Application Creation—Spring Initializer,Toolsuit
5. Spring Boot Starter POM
6. Start/main class in Spring Boot
7. @SpringBootApplication annotation
8. @AutoConfiguration in Spring Boot
9. SpringApplicaiton.run method
10. Spring Boot BootStraping Process
11. IOC container
12. Dependency Injection---CI,SI,FI
13. Autowiring and Qualifier
14. Component Scanning
15. Stereotype Annotation
16. Bean life cycle
17. Banner in Spring
18. Runners in Spring Boot---
ApplicationRunner,CommandLineRunner

Part -2 :- Spring Data JPA


1. What is Persistence Layer
2. Best Practices in Persistence Layer Development
3. ORM Basics
4. Spring Data JPA Introduction
5. Spring ORM vs Spring Data JPA
6. Data jpa Repository Interfaces---CURD Repository,JPA Repository
7. Repository methods
8. findBy methods in Data JPA
9. custom queries in Data JPA
10. Pagination & Sorting
11. Query By Example Executor(QBE)
12. Generators
13. Custom Generators
14. Transaction Management
15. Connection Pooling
Part-3: Spring Web MVC
1. What is Web Application
2. MVC Architecture
3. FrontController Design Pattern
4. Spring web MVC Introduction
5. Spring web MVC advantages
6. Spring web MVC architecture
7. Dispatcher Servlet
8. Handler Mapper
9. Controller
10. ViewResolver
11. Model,ModelAndView and @ModelAttribute
12. Sending Data from Controller to UI and Viceversa
13. Path Param,Query param
14. Spring MVC form tag Library
15. Form Based Applications
16. Spring Boot Actuators
17. Embeded containers
18. H2 Database
19. Form Validations
20. Email Sending in Spring Boot

Part 4:- Restful WebServices:-


1. Distributed Applications
2. Distributed Technologies
3. SOAP vs REST
4. Rest principles
5. Rest Architecture
6. Rest Resource Development
7. Http Methods
8. Http status codes & messages
9. Http Request and Response Format
10. @RestController
11. Controller vs RestController
12. Consumes
13. Produces
14. JSON & Jackson
15. XML & JAX-B
16. Content Type and Accept header
17. Exception Handling in REST Api
18. Swagger Documentation
19. POSTMAN tool
20. Securing Rest API
a. JWT
b. oAuth 2.0
c. Http Baisc Auth
21. Rest Client Development
22. Rest Template
23. Web Client
24. Mono Objects
25. Flux Objects
26. Reactive Programming
Part:5 MicroServices
1. Monolith Architecture
2. Drawbacks of Monolith
3. Load balancer
4. Load Balancer Algorithms—Sticky Session, IP hashing ,Round
Robbin
5. Microservices Evolution
6. Limitations of MicroServices
7. Advantages of Microservices
8. Microservices Architecuture
9. Service Registry (Eureka Server)
10. Service development
11. API Gateway (zuul Proxy)
12. Stock market MicroServices bases App(Mini Project)
13. Circuit Breaker
14. Spring Boot Admin server & Client
15. Distributed Logging using sleuth and zipkin
16. Apache Kafka in Microservice
17. Redis cache in microservice
18. Microservices with Docker
19. Angular integration in Mini Project
20. Microservices unit testing with Junit and Mockito
21. Spring Boot Profiles
22. Working with Multiple Databases
23. Microservices CI & CD
24. Cloud Deployment
25.
26.

Spring Boot folder Structure


.

What is @SpringBootApplicaiton Annotation?


It equals to 3 annotations
1. @SpringBootConfiguration
2. @EnableAutoconfiguation
3. @ComponentScan
It is called as Classlevel Annotation. @SpringBootConfiguration
represents our class as Configuration Class and we can write @Bean
methods in our class
@EnableAutoConfiguration:- provides Auto Configuration functionalities
for our application
@ComponentScan:- Provides functionalities to scan for spring Beans
Available in Application

In Spring we need to enable ComponentScan but its default in Spring


Boot. Object will be created automatically.
Component scan will use the base package naming convention to
identify Spring Beans available in application
What is Base package in Spring Boot?
The package which contains Application.java(start class).

Component Scan will start from Base Package after that it starts the
subpackages. The Packages start with the basepackage name is called
subpackages.
Com.sattibabu--- base package
Com.sattibabu.Beans—will be scanned
Com.sattibabu.Controller ---will be scanned
In.sattibabu --- will not be scanned.

@SpringBootConfiguration:- This annotation represents our class as a


Configuration. To customize the bean creation we can write @Bean
methods in the class. This annotation internally uses the @Configuration
@EnableAutoConfiguration:-It configures the required configurations to
run our Application.
Features of Spring BOOT
Creating IOC
Deploying the project into Emboded Container.
Configuring Front Controller
Connectiong Pool Creation
Embedded DB Support.
@ComponentScan:- Component Scan will start from Base Package
after that it starts the subpackages. The Packages start with the
basepackage name is called subpackages.

Com.sattibabu--- base package


Com.sattibabu.Beans—will be scanned
Com.sattibabu.Controller ---will be scanned
In.sattibabu --- will not be scanned.
How to represent Java class as a Spring Bean?
 The class which is managing by the IOC is called Spring Bean.
 There are several annotations are available to represent our class as
Spring Bean.
@Component,@Service,@Repository,@Controller,@RestController,
@Configuration,@Bean-Method Level Annotaion.

@Service:- is used for Business logic

@Repository :- is used for persistence layer components deals with


Database

@Component:- used for general purpose and used for Spring Bean
@Configuration:- used to represent as a Configuration class.
@Bean:- if we want to customize the Bean creation we will go for
@Bean creation. Bean is a method level annotation rest are Class
level annotation.

09-03-2021
Constuctor Injection:- By Using Parameterized Constructor.
Dependent Object is injected to the Target Object through the
Constructor.

@Autowired
Public class Car{ //Target Class
Private Engine eng;

@Autowired
Public Car(Engine eng){ //Target Constructor.
this.eng=eng;
}
}
Setter Injection:- Dependent Object is injected By Calling Setter
method of the Target. Injecting through Setter Method

@Autowired
Public class Car{

Private Engine eng;


@Autowired
Public void setEng(Engine eng){
This.eng= eng;
}
}
Field Injection:- Dependent Object is Injected into the Target Object
through the Reflection API is called Field Injection. If we use
@Autowired at variable level IOC will perform field Injection.

Accessing private variable outside of the Class by using Reflection


API. When we go for the Field Injection. Whenever we specify
@Autowired at field level . Can we use the private variable outside of
the class Yes by using Reflection API.
10-03-2021
IOC:- IOC is a principle to perform to injecting dependencies.
Field injection is not recommended because it violates the solid
principles of OOPS. It is using the Reflection API.
Autowiring:- Auto wiring is the process of identifying dependent
obejcts and inject into the Target Class
Two types of Autowiring available. Default type of the Autowiring is
byType. Identify dependent bean based on the datatype of the
variable. If the Dependent object is an interface based on the
implemented the class it will inject the object.
1. byType
2. byName
If we want to inject the IEngine object into Car class. It may have multiple
implemented classes . So IOC will be confused which class object to be
injected into IEngine interface. So we will use @Primary for the specific
class to inject into Interface object.

@Component(“de”)
Class DieselEngine implements IEngine{

}
@Component(“pe”)
Class PetrolEngine implements IEngine{

@Autowired
@Qualifier(“de”)
IEngine eng;
Autowiring:- Autowiring is the process of identifying the dependent object
and inject into that target object. It is applicable for only object not into
primitive and not for Wrapper classes.
11-03-2021
Banner in Spring Boot:-
When we run the Spring boot applications spring logo is printing on the
console that is called as Banner. Banner printing is a part of
SpringApplication.run(..)method.
Sprint Boot banner is have 3 below modes:-
1. OFF
2. LOG
3. CONSOLE(DEFAULT).
If we set the LOG banner will be printed in log file as well. We can
customize banner text in Spring Boot by creating banner.txt file in
src/main/resources folder. ASCII characters need to given.
spring.main.banner-mode=off
if we want to off the Banner. In src/main/resources folder.

Runners in the Spring Boot:-


What is Runner and Importance of Runners and Types of Runners?
Two types are available in Spring Boot
1. Application Runner
2. CommandLine Runner
Runners are used to execute the logic only one time once application
bootstrapping is completed.
UseCases:-
Load Data into Cache
Configure cron jobs etc.

If we have runners in boot application then SpringApplication.run(..) method


will call them.
ApplicationRunner and CommandLineRunner are functional interfaces.
Those consists of only one run method which takes arguments as args in
ApplicationRunner.run() and args.getSourceArgs() in
CommandLineRunner.

13-Mar-2021

15-Mar-2021
Persistence Layer:- This is used to Communicate with Database.
Best Practice for Persistence Layer:-
1. For every table we should create one DAO Class. If we don’t follow
this there is a problem of Single Responsibility Principle.
Role_master Role_Master_DAO.java
User_Table User_Table_DAO.java
2. For Every Database Table we should have 4 columns
a. createDate
b. CreatedBy
c. UpdateDate
d. UpdtaedBy
3. For Every Table maintain a Primary Key
a. Primary key---Not Null & Unique
4. If we perform Search operations we should use the indexes in the
table.
5. Create Connection pool to avoid connection Exhausted Problem.
6. Implement soft Delete for tables.--- Delete from Application level
Inactive from the Table.
7. Use Generators to Generate the value for Primary Keys.
8. Write Database Independent Queries.
16-Mar-2021
By using Hibernate also we have to do some boiler plate code.
Insert record using Hibernate
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
------------------------
Configuration cfg=new Configuration();
Cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session hsession=sf.openSession();
Transaction tx=hSession.beginTransaction();
Hsession.save(query);
Tx.close();
Inserting record using Spring JDBC
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-----------------------------
JdbcTemplate jdbcTemplate;
jdbcTemplate.update(sql);
Insert record using spring ORM
HibernateTemplate hibTemplate;
hibTemplate.save(entityObj);

by using JDBC we are dealing with Text Data. When we go for hibernate
we don’t go for text data we will use as objects. We have four options
already why do we go for
Spring Data JPA:- For executing CRUD operations we have to perform
1000 times if we have 1000 tables. It’s again boiler plate code. Data JPA
main purpose is used to reduce the boiler plate code while performing
CRUD operations.

Public interface UserMasterDAO extends CrudRespository{


}
17- Mar-2021
Spring Data JPA provided predefined Interfaces to perform CRUD
operations.
Environment setup for persistence Layer:-
1. Install Database Server ---Oracle
2. Install Database Client Server. ---SQL DEVELOPER

Steps to select the first application using DATA JPA


1. Spring-boot-starter-data-jpa
2. Oracle driver/ mysql driver /postres
3. Create entity class
4. Create Repository Interface by extending CrudRepository
5. Create configuration Datasource properties in application.properties
6. Call the repository methods to call them.
20-Mar-2021
CrudRepository:- CrudRepository is a pre defined interface provided by
Data JPA to perform CRUD operations. CRUD Repository has 11 methods
1. save()
2. saveAll()
3. findById();
4. findAllById();
5. findAll();
6. existsById();
7. count()
8. delete();
9. deleteById()
10. deleteAllById();
11. deleteAll();
we just need to call these methods in our class. We don’t have method
to perform update operation. We can use the save method only to
perform the update operation. When we call the save() method it will
check the record exists with the primary key. If it exists it will update or
otherwise it will insert the Data. 4

spring.jpa.properties.show_sql=true

22-Mar-2021:- No class
23-Mar-2021
When we write HQL queries database will not understand it should be
converted by Dialect classes. We can configure the dialect classes in our
property files.
@query(“ “) ---- HQL query
@query(value=” “, nativeSqlQuery=true);
SQL--- select * from EMP_DTLS will use Table names
HQL Query:- from Employee where empName=”ram”; ---It uses entity class
name and entity properties.

SQL:- select emp_name from EMP_DTLS WHERE EMP_ID=401;


HQL:- select empName from Employee where empId=401;

24-Mar-2021
Spring Data JPA Overview.
CrudRepository is extending from Repository which is a marker interface.
CrudRepository consists of 11 methods.

JpaRepository extends two more interfaces. PagingAndSortingRepository


and QueryByExampleExecutor.
PagingandSortingRepository consists of 2 methods and
QueryByExampleExecutor consists of 6 methods.
We will use Example for Dynamic search.
Pagination:- Dividing the records into multiple pages.
Pagable page=PageRequest(0,3);
Page<UseDtls> findAll=dtslRepository.findAll(page);
findAll.forEach(user->{System.out.println(user);});
25-Mar-2021—No class

26-Mar-2021
Generators:- Generators are used to configure the values to the primary
key. It will use internally Hibernate_sequence for generating Primary key
value.
How to create custom generator in Spring Boot?
@GeneratedValue(generator=”user_Seq”,
strategy=”GenerationType.SEQUENCE”);
If we want to define our own generators
Custom Generators:-
Generators are used to generate the value for Primary key column. There
are certain generators are available based on user requirement we will
create custom generators.
Use case:- TCS emp id
TCS01,TCS02,
OD1,OD2,OD3.
To create custom generators we should implement the IdentifierGenerator
interface. We have generator() method in the interface. We have to write
the logic in that method. The primary key will be devided into two parts.
PrefixOD
Suffix-Number(starts with 1 increment by 1);
Step to Develop a Spring Data JPA with custom Generators.
1. Creating Spring starter project with below dependencies
a. Spring-boot-starter-data-jpa
b. Oracle driver
c. Lombok project
2. Create an entity class using annotations.
3. Create sequence in DB for suffix value generation.
4. Create custom generator class by implementing Identifier Generator
Interface.
5. Configure custom generator in Entity.
6. Create Repository Interface by extending Repository Interface.
Transaction Management:-Unit amount of work is called a Transaction.
30-03-2021
Connection Pooling:-
To perform CRUD operations we need database connection. JDBC
connects with DB by using
Connection con=DriverManager.getConnection(“”);
This is called physical connection.
If we use connection pooling. Data JPA will help to get connection this is
called logical connection.
Spring Boot will use Hikari to connect with Database. If we don’t close
Hikari will close the connections.
We can customize the Hikari Connection pool properties in
Application.properties or Appliction.yml file.
Ideal time for Connection
Min size no of connections
Max size no of connections.
Spring.datasource.hikari.idleTimeout=1000
Spring.datasource.hikari.connectionTimeout=3000
Spring.datasource.hikari.maxLifetime=180000
In SpringBoot 1.x version we have to add the hikari dependency in pom.xml
In springBoot.2.x version its inbuilt property.
31-Mar-2021
Spring MVC:- Spring MVC is one of the module in the Spring frame work.
It supports two types of applications.
1. Web Applications
2. Distributed Application
Advantages of Spring MVC:-
1. It supports loosely coupling
2. It supports form binding. It provides flexibility in form binding
means it will take care of the type casting.
3. It can support multiple presentation technologies.
4. Components roles are clearly defined.
Every request should be handled by individual controller. For avoiding this
we are using Spring MVC architecture. It uses front controller. It will take
care of common logics required for all the controllers.

Spring MVC developed based on the two design patterns


1. MVC architecture
2. Front controller Design pattern
It is a layered architecture maintenance is very easy.
Spring MVC Architecture:-
1. Dispatcher Servlet
2. Handler Mapper
3. Controller
4. ModelAndView
5. View Resolver
6. View

01-Apr-2021
Spring MVC module is developed based on 2 design patterns

1) MVC Design Pattern

2) FrontController Design Pattern


02-Apr-2021

1. Dispatcher Servlet:- Dispatcher Servlet is a pre-defined class


available in Spring MVC and it is responsible to perform pre-
processing and post-processing of a request. DispatcherServlet is
called as Front Controller. Dispatcher Servlet Will Interact with
HandlerMapper to identify Request Handler.
2. Handler mapper:-
3. Controller
4. ModelAndView
5. View Resolver:- DispatcherServlet will use "View Resolver" to
identify location of view files and extension of view files. We will
configure prefix and suffix for View Resolver to identify view files.

prefix = /views/ -------> location of views


suffix = .jsp -----> extension of views

6. View
05-Apr-2021
1. Create Spring Boot Application with below dependencies

1)spring-boot-starter-web
2)tomcat-embed-jasper
3)spring-boot-devtools
2) Create Controller Class using @Controller annotation

3) Create View File with Presentation Logic

4) Configure Server Port and View Resolver in application.properties file

5) Run the application and test it.

In Every Web application we will perform mainly two operations

1) Sending Data From Controller to UI


2) Sending Data from UI to controller
Sending Data From Controller To UI
----------------------------------
-> We can send data from Controller to UI using Model object in the form of key-value pair

Syntax: model.addAttribute(String key, Object value);

model.addAttribute("name", "Ashok");
model.addAttribute("user", userObject);
model.addAttribute("books", booksList);

-> Model data we can access in view file based on key

Syntax : ${key}
We can send direct raw response also from controller using @ResponseBody annotation

@Controller + @ResponseBody = @RestController


import in.ashokit.domain.User;
@Controller
@RequestMapping("/user")
public class UserController {

@GetMapping
public String getUserData(Model model) {

User userObj = new User(101, "Ashok", "[email protected]");

model.addAttribute("user", userObj);

return "user-data";
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>User Data</h3>

User Id : ${user.userId} <br/>


User Name: ${user.username} <br/>
Email : ${user.email}
</body>
</html>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

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

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h3>Books Available</h3>
<table border="1">
<thead>
<tr>
<th>Book Id</th>
<th>Book Name</th>
<th>Book Price</th>
</tr>
</thead>
<tbody>
<c:forEach items="${books}" var="book">
<tr>
<td>${book.bookId}</td>
<td>${book.bookName}</td>
<td>${book.bookPrice}</td>
</tr>
</c:forEach>
</tbody>
</table>

</body>
</html>
07-Apr-2021
We can send data from UI to controller in below ways

1) Request Param
2) Path Param
3) Forms
If we want to send small piece of information then we will use Request Param or Path Param
Request Param and Path Param will represent data in URL directley
Using Forms we can send data in Request Body.

08-Mar-2021
When we submit form then form data will go to server in key-value format.

-> Spring MVC having form binding support. It will capture form data and
will store into object.

-> Form fields keys should match with our class variables then form data
will be store into objet.
-> If we submit form with GET request then form data will be appendend to
URL (It is not secured).

-> Always it is recommended to submit form with POST request so that


form data will go to server in Request Body.

-> To represent POST request we will specify method="POST" in <form/>


tag

<form action="" method="POST">


.........
</form>

-------------------------------------------------------------------------
-> To simplify forms development Spring MVC provided Form Tag library

-> Spring MVC form tag library contains set of tags like below

<form:form>
<form:input>
<form:password>
<form:radioButton> & <form:radioButtons>
<form:select> & <form:option> & <form:options>
<form:checkbox> & <form:checkboxes>
<form:hidden/> etc...
-> Inorder to use spring mvc form tags in jsp, we should add taglib directive
with spring mvc form tags url.
10-Apr-2021
As part of Form tag library several tags are available

form
input
password
radioButton
radioButtons
checkbox
checkboxes
select
option & options
package in.ashokit.domain;

import lombok.Data;

@Data
public class Student {

private String firstName;

private String lastName;

private String gender;

private String course;

private String timings;

}
-------------------------------------------------------------------------
package in.ashokit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import in.ashokit.domain.Student;

@Controller
public class StudentController {

@GetMapping("/student")
public String loadForm(Model model) {
// Form Binding Object
Student s = new Student();
model.addAttribute("student", s);

// return logical view name


return "student";
}

@PostMapping("/student")
public String saveStudent(Student student, Model model) {
System.out.println(student);

model.addAttribute("succMsg", "Registration Successfull");

return "student";
}

}
------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<font color='green'>${succMsg}</font>

<form:form action="student" method="POST" modelAttribute="student">


<table>
<tr>
<td>First Name</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td>Gender</td>
<td><form:radiobutton path="gender" value="M" /> Male
<form:radiobutton
path="gender" value="F" /> Fe-Male</td>
</tr>

<tr>
<td>Course</td>
<td><form:select path="course">
<form:option value="">-Select-</form:option>
<form:option value="java">Java</form:option>
<form:option value="testing">Testing</form:option>
<form:option value="python">Python</form:option>
</form:select></td>
</tr>

<tr>
<td>Timings</td>
<td>
<form:checkbox path="timings" value="mrng"/>Morning
<form:checkbox path="timings" value="noon"/>Afternoon
<form:checkbox path="timings" value="evng"/>Evening
</td>
</tr>

<tr>
<td></td>
<td>
<input type="submit" value="Register"/>
</td>
</tr>

</table>
</form:form>
</body>
</html>
11-Apr-2021
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
package in.ashokit.domain;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Value;

import lombok.Data;

@Data
public class Student {
@NotEmpty(message = "{validation.firstName.notEmpty}")
@Size(min = 3, max = 8, message = "Minimum 3 and Maximum 8 characters are
allowed")
private String firstName;

@NotEmpty(message = "{validation.lastName.notEmpty}")
private String lastName;

@NotEmpty(message = "{validation.email.notEmpty}")
@Email(message = "Please enter a valid e-mail address")
private String email;

private String gender;

private String course;

private String timings;

---------------------------------------------------------------------------------------------
package in.ashokit.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import in.ashokit.domain.Student;
import in.ashokit.service.StudentService;

@Controller
public class StudentController {

@Autowired
private StudentService service;

@GetMapping("/student")
public String loadForm(Model model) {

// Form Binding Object


Student s = new Student();
model.addAttribute("student", s);
// return logical view name
return "student";
}

@PostMapping("/student")
public String saveStudent(@Valid Student s, BindingResult result, Model model) {
System.out.println(s);

if(result.hasErrors()) {
return "student";
}
//store form data in db
model.addAttribute("succMsg", "Registration Successfull");
return "student";
}

@ModelAttribute
private void loadFormData(Model model) {
System.out.println("******* loadFormData() method called ******");
model.addAttribute("genders", service.getGenders());
model.addAttribute("courses", service.getCourses());
model.addAttribute("timings", service.getTimings());
}
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<font color='green'>${succMsg}</font>

<form:form action="student" method="POST" modelAttribute="student">


<table>
<tr>
<td>First Name</td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
<td><form:errors path="email" /></td>
</tr>
<tr>
<td>Gender</td>
<td><form:radiobuttons path="gender" items="${genders}" /></td>
</tr>

<tr>
<td>Course</td>
<td><form:select path="course">
<form:option value="">-Select-</form:option>
<form:options items="${courses}" />
</form:select></td>
</tr>

<tr>
<td>Timings</td>
<td><form:checkboxes items="${timings}" path="timings" /></td>
</tr>

<tr>
<td></td>
<td><input type="submit" value="Register" /></td>
</tr>

</table>
</form:form>
</body>
</html>
package in.ashokit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@SpringBootApplication
public class Application {

public static void main(String[] args) {


SpringApplication.run(Application.class, args);
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new
ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}

@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}

}
-------------------------messages.properties---------------------------------------------

validation.firstName.notEmpty=First name should not be empty


validation.lastName.notEmpty=Last name should not be empty
validation.email.notEmpty=Email should not be empty

You might also like