Manage HTTP headers with Java Servlets: Quick Notes

Servlet & JSPIn Java Servlets API, both HttpServletRequest and HttpServletResponse interfaces (in javax.servlet.http package) provide methods to programatically manipulate HTTP headers. There are a number of standard HTTP headers exchanged between a web server and a client (eg: a browser). "Content-Type" is a commonly used header (which is used to specify MIME type) in Servlets. In this article we are discussing how headers are read/written with Servlet classes.

Reading Headers

A servlet can read HTTP headers sent by a client request using HttpServletRequest interface. This interface has two methods for this.

String getHeader(String headerName)
int getintHeader(String headerName)

Both these methods are similar except getIntHeader() method is used to return value of headers with int type values. Below code shows how value of "User-Agent" header is read from the user request. (HttpServlet.doGet() method is used in the example).


import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {
public void doGet(re, res) throws IOException{
String contentType = request.getHeader("Content-type");
....
}
}

Creating/Writing Headers

A servlet can create a header and send back to the client using HttpServletResponse interface; using the following setter methods.

void setHeader(String headerName, String headerValue)
int setintHeader(String headerName, int headerValue)

Below code shows how a new header named "My_Header" is created and set on response.


import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {
public void doGet(re, res) throws IOException{
response.setHeader("My_Header", "new Header value");
....
}
}

Now the client (generally the browser) will receive this new header.

Check out this stream