Java HttpServletrRequest
HttpServletRequest interface extends the ServletRequest interface.
HttpServletRequest breaks the complete request in below part:
- Request URI
- Parameters
- Attributes
- ServletInputStream
requestURI
The requestURI comes out of request URL as shown below:
For example:
Below is the sample HTTP servlet URL
http://localhost:8080/Myproject/address/info/top.html?studentId=1
In HTTP servlet we get parse below info from HttpServletRequest
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String pathInfo = request.getPathInfo();
String queryStr = request.getQueryString();
OUTPUT:
GetRequestURI → /Myproject/address/info/top.html
GetContextPath → /Myproject
GetServletPath → /address
GetPathInfo → /info/top.html
GetQueryString → info=intro
Parameter:
HttpsServletRequest provides methods to access request parameter (or query String).
Below are list of methods:
getParameter(String parameterName) → This method help us to get request parameter(or query string) value.
request.getParameter(“studentId”)
OUTPUT: 1
getParameterNames() → This method help us to get all request parameter(or query string) Names.
String[] paramNames = request.getParameterNames();
OUTPUT: [“studentId”]
getParameterValues() → This method help us to get all request parameter(or query string) values.
String[] paramValues = request.getParameterValues();
OUTPUT: [“1”]
getHeader() → The HttpServletRequest object also contains request headers as a key and value pairs. Request header contains information related to referrer, content type, content length, etc.
Below is the code snippet to collect header in Servlet class.
String contentType = request.getHeader(“Content-Type”);
OUTPUT: application/json
getSession() → This method returns the current session associated with the request.
getSession(true) →It will create brand new session if not session exist.
getSession(false) →This method will return null if no session exist.
Syntax:
HttpSession session = request.getSession();
session.setAttribute(“studentId”, request.getParameter(“studentId”));
InputStream
getInputStream() → HTTP POST request allows us to send huge data to server as part of request body. HTTP POST request data can be collect as part of InputStream as shown below:
Syntax:
InputStream requestBodyInput = request.getInputStream();
I hope you found out this article interesting and informative. Please share it with your friends to spread the knowledge.
You can follow me for upcoming blogs follow.
Thank you!