getContentLength() Method Example

This method is defined in ServletRequest interface from javax.servlet package and inherited by HttpServletRequest.

With this method, the servlet programmer can know the length of data (through FORM fields like user name etc.) sent by the client. Or to say, the length (in bytes) of query string.

What is query string in servlets?

It is the string containing the name of FORM fields and the data entered by the user in the fields. Field is separated with the value entered by the user with = symbol (see the output screen).

Let us see what Java API says about this method.

  • public int getContentLength():
    Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. For HTTP servlets, same as the value of the CGI variable CONTENT_LENGTH.

The method getContentLength() returns the number of bytes as an integer value, the length of data sent by the client through FORM fields (of text boxes, check boxes etc.).

Let us see the output by writing a program.

HTML Program: ClientData.html


Enter Your Name

Observe, the client uses8888 port number in attribute ACTION.

web.xml entry for ClientInformation servlet


  efgh
  ClientInformation



  efgh
  /jasmine

Servelet Program: ClientInformation.java

import javax.servlet.*; 
import javax.servlet.http.*;
import java.io.*; 

public class ClientInformation extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    int length = req.getContentLength();
    out.println("req.getContentLength() :  " + length);

    out.close();
  }
}

Output screen of ClientData.html with text field filled up as SNRao.

getContentLength()

The output screen when submit button is clicked.

getContentLength()

Observe, the content length is 8 bytes (of t1=SNRao).

Note: With GET method in HTML, the content returned is -1.

Leave a Comment

Your email address will not be published.