Manage HTTP headers with Java Servlets: Quick Notes - Digizol6

Post Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Wednesday, October 15, 2008

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.

4 comments:

  1. thanks for sharing info

    ReplyDelete
  2. Thanks for the notes

    ReplyDelete
  3. This's good, useful for SCWCD.
    Can you add some more of this type quick notes on Servlet?

    ReplyDelete
  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.

    ReplyDelete

Post Top Ad

Responsive Ads Here