getServerPort() Method Example

getServerPort() method is defined in ServletRequest interface from javax.servlet package and inherited by HttpServletRequest.
With getServerPort() method, the Servlet Programmer can know what port number is used by the client from HTML file to call the Servlet.

Let us see what Java API says about this method.

  • int getServerPort():
    Returns the port number to which the request was sent. It is the value of the part after ":" in the Host header value, if any, or the server port where the client connection was accepted on.

The method getServerPort() returns an integer value, the port number used in ACTION attribute of of FORM tag used by the client to call the servlet.

Example on getServerPort()

HTML Program: ClientData.html

Enter Your Name

Observe, the client uses8888 port number in attribute ACTION.

web.xml entry for ClientInformation servlet



Servelet Program:

import javax.servlet.*; 
import javax.servlet.http.*;

public class ClientInformation extends HttpServlet
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    PrintWriter out = res.getWriter();

    int portNumber = req.getServerPort();
    out.println("req.getServerPort() :  " + portNumber);


Output screen of ClientData.html with text field filled up. Anyhow, the text field does not have any purpose here.


The output screen when submit button is clicked.


Leave a Comment

Your email address will not be published.