servlets request interface

www‮‬.theitroad.com

The ServletRequest interface in the Java Servlet API represents an incoming HTTP request from a client. It provides methods to retrieve information about the request, such as the request method, headers, parameters, and attributes.

Here are some of the most commonly used methods of the ServletRequest interface:

  • getMethod(): Returns the HTTP method of the request, such as "GET" or "POST".
  • getParameter(name): Returns the value of a request parameter with the given name, or null if the parameter does not exist.
  • getParameterMap(): Returns a Map of all request parameters and their values.
  • getHeader(name): Returns the value of a request header with the given name, or null if the header does not exist.
  • getHeaderNames(): Returns an enumeration of all request header names.
  • getAttribute(name): Returns the value of an attribute with the given name, or null if the attribute does not exist.
  • setAttribute(name, value): Sets the value of an attribute with the given name.
  • getServletContext(): Returns the ServletContext of the web application that the request is part of.

Here's an example of using the ServletRequest interface to retrieve information about an HTTP request:

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

public class MyServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Get the HTTP method of the request
    String method = request.getMethod();

    // Get a request parameter
    String name = request.getParameter("name");

    // Get a request header
    String userAgent = request.getHeader("User-Agent");

    // Set an attribute on the request
    request.setAttribute("foo", "bar");

    // Get the ServletContext of the web application
    ServletContext context = request.getServletContext();

    // Generate the response
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html><body>");
    out.println("# Request Information:");
    out.println("<p>Method: " + method + "</p>");
    out.println("<p>Name: " + name + "</p>");
    out.println("<p>User-Agent: " + userAgent + "</p>");
    out.println("</body></html>");
  }
}

In this example, we define a new servlet called MyServlet that overrides the doGet() method to handle GET requests. We use various methods of the HttpServletRequest object to retrieve information about the request, such as its HTTP method, parameters, and headers. We also set an attribute on the request and retrieve the ServletContext of the web application. Finally, we generate an HTML response that displays the request information.