2
2
.
.
1
1
.
.
1
1
C
C
r
r
e
e
a
a
t
t
e
e
F
F
i
i
l
l
t
t
e
e
r
r
-
-
U
U
s
s
i
i
n
n
g
g
I
I
m
m
p
p
l
l
e
e
m
m
e
e
n
n
t
t
s
s
F
F
i
i
l
l
t
t
e
e
r
r
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to create Filter Class by using implements Filter.
Code before chain.doFilter(request, response) is executed during HTTP Request.
Code after chain.doFilter(request, response) is executed during HTTP Response.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_filter_create (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
Create Package: filters (inside main package)
– Create Class: MyFilter.java (inside controllers package)
MyController.java
package com.ivoronline.springboot_filter_create.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public String hello() {
System.out.println("Controller: Code from Controller");
return "Hello from Controller";
}
}
MyFilter
MyController
Request
Response
http://localhost:8080/Hello
Request
Response
hello()
MyFilter.java
package com.ivoronline.springboot_filter_create.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//THIS CODE IS EXECUTED DURING HTTP REQUEST
System.out.println("MyFilter : Code for HTTP Request");
//CALLS
// - doFilter() METHOD OF THE NEXT FILTER IN CHAIN
// - Endpoint IF THERE ARE NO MORE FILTERS IN CHAIN
//RETURNS FROM THIS METHOD DURING HTTP RESPONSE
// - CAUSING SUBSEQUENT CODE TO BE EXECUTED DURING HTTP RESPONSE
// - CAUSING FILTERS TO BE EXECUTED IN REVERSE ORDER DURING HTTP RESPONSE (BUT ONLY BELOW CODE)
chain.doFilter(request, response); //DIVIDES HTTP REQUEST AND RESPONSE CODE
//THIS CODE IS EXECUTED DURING HTTP RESPONSE
System.out.println("MyFilter : Code for HTTP Response");
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
Console
MyFilter : Code for HTTP Request
Controller: Code from Controller
MyFilter : Code for HTTP Response
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>