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 parameters | getParameter("username") |
Read request body (e.g., POST data) | getInputStream() or getReader() |
Get client IP, hostname | getRemoteAddr() , getRemoteHost() |
Access request attributes | getAttribute() , setAttribute() |
Get content length and encoding | getContentLength() , getCharacterEncoding() |
Work with input streams | Binary or character reading of body |
Detect protocol/port/server info | getProtocol() , getServerPort() |
🔧 Common Methods in ServletRequest
Method | Description |
---|---|
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
Feature | ServletRequest | HttpServletRequest |
---|---|---|
Protocol-agnostic | ✅ Yes | ❌ No (HTTP-specific only) |
HTTP methods (GET/POST/etc.) | ❌ Not available | ✅ Yes |
Header access | ❌ Not available | ✅ getHeader() , getCookies() |
Session support | ❌ Not available | ✅ getSession() |
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
Feature | Description |
---|---|
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 |