HttpServletRequest
HTTP Header Records
- Remember these?
GET / HTTP/1.1
Host: localhost:4444
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
- When a browser submits a request to a Java Application Server, like tomcat, the header records are parsed set into an object that is an
HttpServletRequest
type. - All the information that is part of the browser request is available via this object.
-
The object is delivered to a servlet or JSP page in a method.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
In addition to the header records, there is a lot more information available through this object.
Getting Information from the HttpServletRequest Object in a Servlet
-
In a servlet we get information from the request object like this.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.print("<HTML>"); out.print("<HEAD><TITLE>Sample Output</TITLE></HEAD>"); out.print("<BODY>"); out.print("<h1>Server Name</h1>"); out.print("<p>" + request.getServerName() + "</p>"); out.print("</BODY>"); out.print("</HTML>"); out.close(); }
-
The statement
request.getServerName()
returns a string with the server’s names.
HttpServletRequest is also an Attribute Map
- An Attribute Map is a map with keys that are strings and values that can be any object.
-
We know three types of Maps now.
-
A normal Map
- Key: any object
- Value: any object
-
A Property Map
- Key: String
- Value: String
-
An Attribute Map
- Key: String
- Value: any object
-
-
Here are some of the methods we can use with an HttpServletRequest object.
setAttribute("key", <value>)
getAttribute("key")
removeAttribute("key")
-
Example:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("test", "This is just a test!"); ... }