servlet

Get Request Header in Servlet

This is an example on how to get Request Headers in a Servlet. This is to make it easy for the programmer to parse an HTTP request object and decide on the response you will provide. You will find this example useful if you want to get a known header.

In short in order to get request headers in a Servlet, one should follow these steps:

  • Create a handleRequest method so you can use it both in doGet and doPost methods.
  • Use HttpServletRequest.getHeaders(headerName) to get the value of a specific header.

 
Here is the code:

package com.javacodegeeks.snippets.enterprise;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetRequestHeaderInServlet extends HttpServlet {

	private static final long serialVersionUID = -2128122335811219481L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		handleRequest(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
		handleRequest(req, res);
	}

	public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws IOException {

		PrintWriter out = res.getWriter();
		res.setContentType("text/plain");

		String headerName = "user-agent";

		String headerValue = req.getHeader(headerName);
		out.write(headerName);
		out.write(" = ");
		out.write(headerValue);
		out.write("n");

		out.close();

	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">

	<display-name>JCG Snippets Web Project</display-name>

	<servlet>
		<servlet-name>JCG Snippets Application</servlet-name>
		<servlet-class>com.javacodegeeks.snippets.enterprise.GetRequestHeaderInServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>JCG Snippets Application</servlet-name>
		<url-pattern>/jcgservlet</url-pattern>
	</servlet-mapping>

</web-app>

URL:

http://myhost:8080/jcgsnippets/jcgservlet

Output:

user-agent = Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0

 
This was an example on how to get Request Headers in a Servlet.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button