In this section we will discuss that how can you find out the request header in java Servlet.
Getting Request Header
In this section we will discuss that how can you find out the request header in java Servlet.
In the example given below we are discussing how all the request header can be retrieved. To accomplish this problem I used methods getHeadersNames(), & getHeaders().
getHeaderNames() : This method is a part of HttpServletRequest interface. All the contained header names returned as an enumeration by this request. If there is no header in the request then an empty enumeration is returned by this method.
syntax : public (java.util)Enumeration getHeaderNames();
getHeaders() : This method is a part of HttpServletRequest interface. The parameter takes a String Object Enumeration and gives back all the requested header values as an Enumerated String Object.
Example :
import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; public class GetHttpRequestHeader extends HttpServlet{ Enumeration enm,header; String headerName,headerValues; public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{ PrintWriter out = res.getWriter(); out.println("List of Request headers"); enm= req.getHeaderNames(); out.println("\n"); out.println("HeaderName\t HeaderValues"); while(enm.hasMoreElements()) { headerName=(String)enm.nextElement(); header= req.getHeaders(headerName); if(header!=null){ while(header.hasMoreElements()){ headerValues= (String) header.nextElement(); out.println("\n"+headerName+" :\t"+headerValues); } } } } }
XML mapping (web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>bipul4</servlet-name> <servlet-class>GetHttpRequestHeader</servlet-class> </servlet> <servlet-mapping> <servlet-name>bipul4</servlet-name> <url-pattern>/GetHttpRequestHeader</url-pattern> </servlet-mapping> </web-app>
Output : when you will execute this program you will get the following result.
[ 0 ] Comments