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.
Example on getServletPath()
Client Program: ClientData.html
web.xml entry for ClientInformation servlet
efgh
ClientInformation
efgh
/jasmine
Let us go to the coding part.
Server 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();
String str = req.getServletPath();
out.println("req.getServletPath() : " + str);
out.close();
}
}
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.