JAVA-86: spring-boot-add-filter

This commit is contained in:
Krzysiek 2020-03-15 20:36:28 +01:00
parent 7b7f988f88
commit b19dbb9c20
7 changed files with 205 additions and 0 deletions

View File

@ -9,3 +9,4 @@ This module contains articles about Spring Boot customization
- [Create a Custom FailureAnalyzer with Spring Boot](https://www.baeldung.com/spring-boot-failure-analyzer)
- [Spring Boot: Customize Whitelabel Error Page](https://www.baeldung.com/spring-boot-custom-error-page)
- [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class)
- [How to Define a Spring Boot Filter?](https://www.baeldung.com/spring-boot-add-filter)

View File

@ -0,0 +1,23 @@
package com.baeldung.bootcustomfilters;
import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
// uncomment this and comment the @Component in the filter class definition to register only for a url pattern
// @Bean
public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter() {
FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new RequestResponseLoggingFilter());
registrationBean.addUrlPatterns("/users/*");
return registrationBean;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.bootcustomfilters;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Boot application
* @author hemant
*
*/
@SpringBootApplication
public class SpringBootFiltersApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootFiltersApplication.class, args);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.bootcustomfilters.controller;
import com.baeldung.bootcustomfilters.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Rest controller for User
* @author hemant
*
*/
@RestController
@RequestMapping("/users")
public class UserController {
private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
@GetMapping("")
public List<User> getAllUsers() {
LOG.info("Fetching all the users");
return Arrays.asList(
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"),
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"),
new User(UUID.randomUUID().toString(), "User1", "user1@test.com"));
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.bootcustomfilters.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* A servlet filter to log request and response
* The logging implementation is pretty native and for demonstration only
* @author hemant
*
*/
@Component
@Order(2)
public class RequestResponseLoggingFilter implements Filter {
private final static Logger LOG = LoggerFactory.getLogger(RequestResponseLoggingFilter.class);
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
LOG.info("Initializing filter :{}", this);
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
LOG.info("Logging Request {} : {}", req.getMethod(), req.getRequestURI());
chain.doFilter(request, response);
LOG.info("Logging Response :{}", res.getContentType());
}
@Override
public void destroy() {
LOG.warn("Destructing filter :{}", this);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.bootcustomfilters.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* A filter to create transaction before and commit it once request completes
* The current implemenatation is just for demo
* @author hemant
*
*/
@Component
@Order(1)
public class TransactionFilter implements Filter {
private final static Logger LOG = LoggerFactory.getLogger(TransactionFilter.class);
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
LOG.info("Initializing filter :{}", this);
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
LOG.info("Starting Transaction for req :{}", req.getRequestURI());
chain.doFilter(request, response);
LOG.info("Committing Transaction for req :{}", req.getRequestURI());
}
@Override
public void destroy() {
LOG.warn("Destructing filter :{}", this);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.bootcustomfilters.model;
/**
* User model
* @author hemant
*
*/
public class User {
private String id;
private String name;
private String email;
public User(String id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
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;
}
}