@WebServlet("/example") public class ExampleServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int contentLength = request.getContentLength(); System.out.println("Content length of the request: " + contentLength); } }
@WebFilter(urlPatterns = {"/*"}) public class ExampleFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; int contentLength = httpServletRequest.getContentLength(); System.out.println("Content length of the request: " + contentLength); chain.doFilter(request, response); } }In this example, the getContentLength method is used to obtain the content length of each incoming HTTP request. The obtained value is then displayed using the print statement. This filter can be used for logging purposes or to perform some authentication/authorization logic based on the length of the incoming request. The javax.servlet.http.HttpServletRequest class that provides the getContentLength method is part of the Java Servlet API library. This library is included in the javax.servlet package.