Java News Tips Software
Java News Tips Software | Contact | Facebook | Twitter RSS

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.

Labels: ,


4 Comments

  1. Anonymous Anonymous on October 22, 2008 3:06 PM  
    thanks for sharing info
  2. Anonymous Anonymous on April 30, 2009 9:30 AM  
    Thanks for the notes
  3. This's good, useful for SCWCD.
    Can you add some more of this type quick notes on Servlet?
  4. Great Post. I have not been visiting the site recently. Took a visit again and there were some great comments on the site. Excellent post. Keep up the good work.
ABOUT AUTHOR
Page Views :
Email :
PREVIOUS ARTICLES
Select Month:
TOP
Free counter and web stats