Java.Servlets.What Is ServletRequest?

The ServletRequest interface is your main gateway to reading incoming data from a client (browser, mobile app, etc.) in a Java web application.

It lets you extract everything about the request — like parameters, headers, body, input streams, and metadata.

📦 What Is ServletRequest?

ServletRequest is an interface provided by the Servlet API:

javax.servlet.ServletRequest

It is used by the servlet container to pass client request data to your servlet.

✅ Responsibilities of ServletRequest

You Can Use It To…Example
Get query/form parametersgetParameter("username")
Read request body (e.g., POST data)getInputStream() or getReader()
Get client IP, hostnamegetRemoteAddr(), getRemoteHost()
Access request attributesgetAttribute(), setAttribute()
Get content length and encodinggetContentLength(), getCharacterEncoding()
Work with input streamsBinary or character reading of body
Detect protocol/port/server infogetProtocol(), getServerPort()

🔧 Common Methods in ServletRequest

MethodDescription
getParameter(String name)Get a form/query parameter value
getParameterMap()Get all parameters as a map
getInputStream()Read raw binary data from body
getReader()Read character stream (e.g., JSON payload)
getAttribute(String name)Get an attribute (used to pass data between filters)
setAttribute(String, Object)Set attribute (used in filters/forwarding)
getRemoteAddr()Get client IP address
getContentType()Get MIME type of incoming data
getContentLength()Get body length in bytes

🧪 Example: Read Form Parameters

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    res.getWriter().write("Username: " + username);
}

📤 ServletRequest vs HttpServletRequest

FeatureServletRequestHttpServletRequest
Protocol-agnostic✅ Yes❌ No (HTTP-specific only)
HTTP methods (GET/POST/etc.)❌ Not available✅ Yes
Header access❌ Not availablegetHeader(), getCookies()
Session support❌ Not availablegetSession()
Usage in HTTP apps✅ But usually cast to HttpServletRequest✅ Native support

So, while ServletRequest is useful, in HTTP apps you almost always work with its subclass HttpServletRequest, which gives you headers, sessions, cookies, methods, etc.

✅ Summary

FeatureDescription
What is it?Interface for reading incoming client data
Who provides it?Servlet container
When used?Passed into doGet(), doPost(), or filters
Works with…Parameters, attributes, body, encoding, etc.
Use HttpServletRequest for…HTTP-specific features like headers and sessions
This entry was posted in Без рубрики. Bookmark the permalink.