Reading:
HttpServletRequest Object

HttpServletRequest Object

Metamug
HttpServletRequest Object

Getting Parts of a URL From the HttpServletRequest Object

What is a HttpServletRequest ?

When a user sends a http request, the Servlet container creates a HttpServletRequest object which contains various information about the request.

HttpServletRequest extends the ServletRequest interface and it is passed to the service method (doGet(), doPost(), etc.) of the Servlet to handle various requests.

We will create a method to see the request information contained in HttpServletRequest.

public static String getURLinfo(HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();

    String url = req.getRequestURL().toString();
    String queryString = req.getQueryString();
    if (queryString != null) {
        url = url+'?'+queryString;
    }
    sb.append("url: ").append(url);
    sb.append("\n");

    String uri = req.getRequestURI();
    sb.append("uri: ").append(uri);
    sb.append("\n");

    sb.append("query: ").append(queryString);
    sb.append("\n");

    String scheme = req.getScheme();
    sb.append("scheme: ").append(scheme);
    sb.append("\n");

    String serverName = req.getServerName();
    sb.append("server name: ").append(serverName);
    sb.append("\n");

    int serverPort = req.getServerPort(); 
    sb.append("port: ").append(serverPort);
    sb.append("\n");

    String contextPath = req.getContextPath();
    sb.append("context path: ").append(contextPath);
    sb.append("\n");

    String servletPath = req.getServletPath();
    sb.append("servlet path: ").append(servletPath);
    sb.append("\n");

    return sb.toString();
}

If you try this servlet method with this url http://localhost:8080/webapp/src/movie?id=1, you will get the following output

url: http://localhost:8080/webapp/src/movie?id=1
uri: /webapp/src/movie
query: id=1
scheme: http
server name: localhost
port: 8080
context path: /webapp
servlet path: /src


Icon For Arrow-up
Comments

Post a comment