Close

Java Servlet - @WebFilter Examples

Java Servlet JAVA EE 

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "profiler",
urlPatterns = {"/search/*"},
initParams = @WebInitParam(name = "env", value = "dev"))
public class Profiler implements Filter {

private FilterConfig filterConfig;

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

if ("dev".equals(filterConfig.getInitParameter("env"))) {
long time = System.currentTimeMillis();
chain.doFilter(request, response);

time = System.currentTimeMillis() - time;
String url = request instanceof HttpServletRequest ?
((HttpServletRequest) request).getRequestURL().toString() : "N/A";

System.out.println("Time taken for request to complete: " + time
+ "ms");
System.out.println("Request url : " + url);
} else {
chain.doFilter(request, response);
}
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}


@Override
public void destroy() {
}
}
Original Post




Using Filter to log request and response headers.

package com.logicbig.example;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@WebFilter(urlPatterns = {"/*"})
public class HeaderLogFilter implements Filter {

@Override
public void init (FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;

System.out.println("----- Request ---------");
Collections.list(req.getHeaderNames())
.forEach(n -> System.out.println(n + ": " + req.getHeader(n)));

chain.doFilter(request, response);

System.out.println("----- response ---------");

rep.getHeaderNames()
.forEach(n -> System.out.println(n + ": " + rep.getHeader(n)));

System.out.println("response status: " + rep.getStatus());
}

@Override
public void destroy () {
}
}
Original Post




See Also