Creating a Filter in SAP Commerce Cloud (Hybris)
Prerequisite
Having hands-on knowledge of filters in servlets. Knowing the Spring MVC flow will be helpful.
Introduction
In Spring MVC, every request from the front end or any browser is first sent to the dispatcher servlet. The dispatcher then forwards the request to the appropriate controller and method.
Before reaching the dispatcher servlet, the request first passes through a filter, where the doFilter
method processes the request and response.
Adding a Filter to the Existing Filter Chain (Step-by-Step Process)
Filters are essential in SAP Commerce Cloud (Hybris) as they allow developers to hook into the request-response lifecycle. They are commonly used for:
- Logging
- Authentication
- Request manipulation
- Custom operations
Custom Logging Filter Implementation
package com.simplified.storefront.filters; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.web.filter.OncePerRequestFilter; /** * LoggerFilter is a custom filter that logs incoming HTTP requests and their processing time. * This filter extends OncePerRequestFilter to ensure it runs only once per request. */ public class LoggerFilter extends OncePerRequestFilter { // Logger instance for logging request details private static final Logger LOGGER = Logger.getLogger(LoggerFilter.class); /** * This method intercepts incoming requests, logs their details, and measures processing time. * * @param req The HttpServletRequest object representing the client request * @param res The HttpServletResponse object representing the server response * @param filterChain The FilterChain to continue request processing */ @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException { // Capture the start time of request processing long startTime = System.currentTimeMillis(); // Retrieve HTTP method (GET, POST, etc.) String methodName = req.getMethod(); // Get the requested URL String reqUrl = req.getRequestURI(); // Get query parameters if present, otherwise use an empty string String queryStr = req.getQueryString() != null ? req.getQueryString() : ""; // Log the incoming request details LOGGER.info("Incoming request: " + methodName + " " + reqUrl + "?" + queryStr); // Proceed with the filter chain (pass the request to the next filter or controller) filterChain.doFilter(req, res); // Calculate the total processing time long timeForExecution = System.currentTimeMillis() - startTime; // Log the response status and processing time LOGGER.info("Response Status: " + res.getStatus() + " | Processing Time: " + timeForExecution + " ms"); } }
Registering the Filter in SAP Commerce Cloud
To add this filter in SAP Commerce Cloud, follow these steps:
1️⃣ Add a Spring Bean in spring-filter-config.xml
<bean id="customLoggingFilter" class="com.simplified.storefront.filters.LoggerFilter" />
2️⃣ Add the Filter to the Filter Chain
<util:list id="defaultStorefrontTenantDefaultFilterChainList"> <ref bean="hybrisSpringSessionFilter"/> <ref bean="log4jFilter"/> <ref bean="storefrontSessionFilter"/> <ref bean="accMediaFilter"/> <ref bean="addOnDevelopmentFilter"/> <ref bean="requestLoggerFilter"/> <ref bean="polyglotPersistenceCallbackFilter"/> <ref bean="cmsSiteFilter"/> <ref bean="storefrontFilter"/> <ref bean="urlEncoderFilter"/> <ref bean="fileUploadFilter"/> <ref bean="springSecurityFilterChain"/> <ref bean="anonymousCheckoutFilter"/> <ref bean="consentFilter"/> <ref bean="cartRestorationFilter"/> <ref bean="customerLocationRestorationFilter"/> <ref bean="customLoggingFilter"/> </util:list>
Deploying and Testing the Filter
1️⃣ Build the project and restart the server:
ant all && hybrisserver debug
2️⃣ Check the logs for the request logging output.
Expected Output in Logs
INFO | jvm 1 | main | 2025/02/16 20:50:58.093 | INFO [hybrisHTTP25] [LoggerFilter] Incoming Request: GET /trainingstorefront/electronics/en/Open-Catalogue/Data-storage/Flash-Memory/2GB-SD-Card/p/443175? INFO | jvm 1 | main | 2025/02/16 20:51:12.065 | INFO [hybrisHTTP35] [LoggerFilter] Response Status: 200 | Processing Time: 73943 ms
Conclusion
By implementing a custom filter, we were able to log incoming HTTP requests, track response status, and measure request processing time. This can be extended further to handle authentication, error tracking, or performance monitoring in SAP Commerce Cloud (Hybris). 🚀
Comments