jsp
Get Request Header in JSP page
In this example we shall show you how to get the Request Header in a JSP page. When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. To get the Request Header in a JSP page and get the information it has one should perform the following steps:
- Inside the
<%code fragment%>scriptlet use the request object, that is an instance of ajavax.servlet.http.HttpServletRequest. The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc. - Use the
getMethod()API method ofjavax.servlet.http.HttpServletRequestto get the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. - Use the
getRequestURI()API method ofjavax.servlet.http.HttpServletRequestto get the part of this request’s URL from the protocol name up to the query string in the first line of the HTTP request. - Use the
getProtocol()API method ofjavax.servlet.http.HttpServletRequestto get the name and version of the protocol of the request. - Use the
getRemoteHost()API method ofjavax.servlet.http.HttpServletRequestto get the fully qualified name of the client that sent the request. - Use the
getRemoteAddr()API method ofjavax.servlet.http.HttpServletRequestto get the Internet Protocol (IP) address of the client that sent the request,
as described in the code snippet below.
GetRequestHeader.jsp
<%@ page import="java.util.Random"%>
<html>
<head>
<title>Java Code Geeks Snippets - Get Request Header in JSP Page</title>
</head>
<body>
Arbitrary Header:
The user agent is <%= request.getHeader("user-agent") %>
Implicit Headers:
Request method:
<%= request.getMethod() %>
Request URI:
<%= request.getRequestURI() %>
Request protocol:
<%= request.getProtocol() %>
Remote Host:
<%= request.getRemoteHost() %>
Remote Address:
<%= request.getRemoteAddr() %>
</body>
URL:
http://myhost:8080/jcgsnippets/GetRequestHeader.jsp
Output:
Arbitrary Header: The user agent is Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0 Implicit Headers: Request method: GET Request URI: /jcgsnippets/GetRequestHeader.jsp Request protocol: HTTP/1.1 Remote Host: 127.0.0.1 Remote Address: 127.0.0.1
This was an example of how to get Request Header in a JSP page.
