Spring Framework Updated
Spring Framework Updated
Introduction
The Spring Framework provides a patterns and infrastructure for
modern Java-based enterprise applications on any kind of deployment
platform.
Applications of Spring Framework
Large Scale Enterprise Application Developments
Web Application Development
Desktop Application Development
What does Spring Framework provide?
Application Context and Dependency Injection
Easy Communication with Databases
Spring JDBC, Database Access Object(DAO), Object Relational Mapping, Java
Persistence API(JPA)
Spring MVC
Controller, Model, View
Builds Secure Web Applications
Spring Security API
Can be Integrated with Other Frameworks
Integrated with Hibernate, Structs
Testing becomes easy
Spring is not only Framework, it is Eco System for Large Scale Software Application Developments
https://spring.io/projects
Spring Framework Runtime Architecture
Core Container
The Core Container consists of the Core, Beans, Context, and
Expression Language modules.
Core module provides the fundamental parts of the framework such
as container, Inversion of Control(IoC) and Dependency
Injection(DI).
Bean module provides collection of Java Components with specific
tasks ( Ex. Inventory Service, Product Service)
Expression Language for querying and manipulating data or object
at runtime.
Context – Application Runtime Environment
Framework (Inversion of Control(IoC))
Traditional Programming Framework
Difference between Framework and Libraries
Libraries
Your application logic calls library
Framework
The Framework calls your logic when its time.
https://start.spring.io
Click Next
Select Dependencies
Spring Boot Dev Tools
Spring Web
Thymeleaf Template
Finish
Project Creation in Progress
Spring project structure
ExampleApplication.java
- This is the Spring Boot main class that bootstraps
the project.
static—This folder is where you can place any static
content (images, stylesheets, JavaScript, and so forth)
that you want to serve to the browser
templates—This folder is where you’ll place template files
that will be used to render content to the browser. It’s
initially empty, but you’ll add a Thymeleaf template soon.
@SpringBootApplication
- annotation clearly signifies that this is a Spring Boot application.
- This annotation combines three other annotations:
@SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan
@ComponentScan - This lets you declare other classes with annotations like @Component,
@Controller, @Service, and others,
Writing a Spring application
Spring comes with a powerful web framework known as Spring MVC.
Spring Web MVC Handles the Web HTTP Request and Update the
View Page.
Creating Controller
Add a new Java Class
Create a class “HomeController”
Convert the class as Controller and add Request Method
Annotations
@Controller - indicates that a particular class serves the role of a
controller
import org.springframework.stereotype.Controller;
@RequestMapping("/") - the annotation is used to map web
requests to Spring Controller methods
import org.springframework.web.bind.annotation.RequestMapping;
@ResponseBody - tells a controller that the object returned is
automatically serialized into JSON and passed back into the
HttpResponse object.
import org.springframework.web.bind.annotation.ResponseBody;
HomeController
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping("/")
@ResponseBody
public String index() {
return "Welcome to Spring Application!";
}
}
Execute the Application
Open Browser
http://localhost:8080/
Alternate way of @RequestMapping
@RequestMapping(value={"/"}, method=RequestMethod.GET)
public String index() {
return "Welcome to Spring Application!";
}
Request Mapping Annotations
Designing the view
After the controller is finished with its work, it’s time for the
view to get going.
Spring provides ‘thymeleaf’ view template and it needs to be
installed via following dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Create a HTML view
Add html file inside templates folder
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to View Page</h1>
</body>
</html>
Display view from Controller
To display view page from controller, the controller method
should return view file name without .html.
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/")
public String index() {
return "home";
}
}
Run the project
Model
Model is spring class used to hold data
Model defines a holder for model attributes and is primarily
designed for adding attributes to the model.
@Controller
public class HomeController {
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("name", "John David");
return "home";
}
}
Bind the Model Attribute in View
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to View Page</h1>
<p>
Welcome <span th:text='${name}'></span>
</p>
</body>
When the template is rendered into HTML, the body of the <p> element will be replaced
</html>
with the value of the servlet request attribute whose key is “name".
The th:text attribute is a Thymeleaf-namespaced attribute that performs the
replacement.
The ${} operator tells it to use the value of a request attribute (“name", in
this case).
Add Arrays in Model
@Controller
public class HomeController {
@RequestMapping("/")
public String index(Model model) {
return "home";
}
}
Bind Array items in View
<!DOCTYPE html> Thymeleaf provides you with 'each' loop, and you can use
<html> it through the th:each attribute.
<head>
<meta charset="ISO-8859-1"> The <th:block> tag is a virtual tag in
<title>Insert title here</title> the Thymeleaf, it does not correspond to
</head> any HTML tags, but it is useful in many cases, for
<body> example, you can set the th:each attribute in this
<h1>Welcome to View Page</h1> tag.
<p>
Welcome <span th:text='${name}'></span>
</p>
<p>Your Skills are..</p>
<ol>
<th:block th:each='item : ${talents}'>
<li th:text='${item}'>
</th:block>
</ol>
</body>
</html>
ModelAndView
ModelAndView is a spring class which holds both Model and
View
@RequestMapping({"/","/home"})
public ModelAndView homePage(ModelAndView mv) {
mv.addObject("data", "Apple");
mv.setViewName("home");
return mv;
}
Processing Form Submission
HTML form data will be submitted via HTTP get or post
method.
Controller method can use @GetMapping, @PostMapping and
@RequestMapping to receive the data.
Spring binds the data using Java Object which needs to be created
with required instance variables, setter and getter methods.
A reference variable of Java Object needs to be specified in the
controller method to bind the data from HTML form automatically.
Processing Form Submission
Example: You want to submit name and location of a person
to server through HTML form fields
<form action="/save" method="get"> home.html
Name: <input type='text' name='name'>
<br><br>
Location: <input type='text' name='location'>
<br><br>
<button type="submit">Submit</button>
</form>
Processing Form Submission
Create a Java Class to represent two data such as name and location
and include setter and getter methods.
public class User {
private String name;
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
Processing Form Submission
Create Controller Method to receive data from HTML form.
@Controller
public class HomeController {
@RequestMapping(value={"/"}, method=RequestMethod.GET)
public String homePage() {
return "home";
}
@RequestMapping(value="/save", method=RequestMethod.GET)
public String saveUser(User userob, Model model)
{
model.addAttribute("obj", userob);
return "view";
}
}
Here, homepage() method send ‘home.html’ as response.
And, when form is submitted, saveUser() method will be called and
the form fields name and location are bound to properties of User object
Processing Form Submission
Display the data in ‘view.html’
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<p th:text='${obj.name}' />
<p th:text='${obj.location}' />
</body>
</html>
Processing Form Submission
Alternate Controller Annotations
@GetMapping , @PostMapping
@Controller
public class HomeController {
@GetMapping("/")
public String homePage() {
return "home";
}
@PostMapping(value="/save")
public String saveUser(User userob, Model model)
{
model.addAttribute("obj", userob);
return "view";
}
}
Validating form input
When user submit data to server, it may be invalid according to the
requirement of your application.
Hence, Form validation is required to ensure the data submitted via
HTML form is valid.
Fortunately, Spring supports Java’s Bean Validation API, This makes it
easy to declare validation rules in your application code.
And with Spring Boot, the Validation API and the Hibernate
implementation of the Validation API are automatically added to the
project as transient dependencies of Spring Boot’s web starter.
How to Apply Validation
Declare validation rules on the Data class that is to be
validated.
Specify that validation should be performed in the
controller methods that require validation.
Modify the form views to display validation errors.
The Validation API offers several annotations that can
be placed on properties of domain objects to declare
validation rules.
Declaring validation Annotation
jakarta.validation.constraints
@NotBlank
@NotEmpty
@NotNull
@Min
@Max
@Pattern
Model Class
public class User {
@NotBlank(message="* Id must not be blank!!!")
private String id;
@NotBlank(message="* Name must not be blank!!!")
private String name;
@NotBlank(message="* Name must not be blank!!!")
private String email;
@NotBlank annotation check the data field is empty or not
public String getId() {
return id; Here, the id, name, and email variables used to hold the
}
public void setId(String id) {
data from HTML form
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
HomeController
@Controller
public class HomeController {
@GetMapping("/")
public String index(@ModelAttribute("user") User user) {
return "home";
}
@PostMapping("/save")
public String update(@Valid User userob,BindingResult errors, Model model)
{
if(errors.hasErrors()) {
return "home";
}else {
model.addAttribute("status", "success");
model.addAttribute("userob", userob);
return "view";
}
}
When user make request to “/” it will display home.html form
}
where the User class data will be bounded for validation using @ModelAttribute annotatin
Annotations used
@ModelAttribute
It is used to bind the data variables of User class with form fields using
th:object and th:field attributes.
@Valid
It is used to validate the HTML form fields against the validator mentioned in User
class using @NotBlank validator.
If there is an error, the BindingResult object captures the errors and it can be
checked using hasErrors() method, if it is true, the HTML form can be redisplayed
with error message using th:if and th:errors
home.html
<!DOCTYPE html> th:errors
<html> display field-specific error messages
<body>
<style>
span {color:red;}
</style>
<form action="/save" method="post" th:object="${user}">
Id: <input type="text" th:field="*{id}">
<span th:if="${#fields.hasErrors('id')}" th:errors="*{id}"></span>
<br><br>
Name: <input type="text" th:field="*{name}">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
<br><br>
Email: <input type="text" th:field="*{email}">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
<br><br>
<input type="submit" value="Save">
<br><br>
</form> Thymeleaf offers an inbuilt #fields.hasErrors() method that returns a boolean
</body> depending on whether any errors exist for a given field. Combining it with
</html> a th:if we can choose to display the error if it exists:
view.html
<p th:text="${status}"></p>
<hr>
<p>User Details</p>
<p th:text="${'ID:' + userob.id}"></p>
<p th:text="${'Name: ' + userob.name}"></p>
<p th:text="${'Email: ' + userob.email}"></p>
Output
Working with data
Reading and writing data with JDBC
Spring JDBC support is rooted in the JdbcTemplate class.
JdbcTemplate provides a means by which developers can
perform SQL operations against a relational database
Before you can start using JdbcTemplate, you need to add it to your
project classpath.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Working with data
You’re also going to need a database where your data
will be stored.
Embedded Database - H2 Database
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Create a Model class