getServletPath() Method Example

Programmer uses getServletPath() method to retrieve the alias name used by client. getServletPath() Method is defined in ServletRequest inherited by HttpServletRequest.

This program uses getServletPath() of HttpServletRequest to retrieve the alias name (of <servlet-mapping>) tag. Client uses this alias name to call the Servlet.

Following is the method signature. Method is defined in HttpServletRequest interface.

public abstract java.lang.String getServletPath();

Example on getServletPath()

Client Program: ClientData.html

Enter Your Name

web.xml entry for ClientInformation servlet



Let us go to the coding part.

Server 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();

    String str = req.getServletPath();
    out.println("req.getServletPath()  :  " + str);


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


The output screen when submit button is clicked.


Observe, the getServletPath() prints just the alias name and not complete URL. To retrieve complete URL, use getRequestURL() method of HttpServletRequest.

Pass your comments and suggestions on this tutorial "getServletPath() Method Example". It improves the quality of site.

Leave a Comment

Your email address will not be published.