June 18, 2011

Difference between addHeader and setHeader methods on the HttpServletResponse

Note: To test this example, use the Firefox browser with the 'Live HTTP Headers' add-on of Mozilla installed in firefox. Access this link from firefox - https://addons.mozilla.org/en-US/firefox/addon/live-http-headers/

The setHeader() method on the HttpServletResponse object allows setting a new header/value pair in the HTTP Response message. If a header with the same name already exists, the method will overwrite the value with the new value passed in the method.

The addHeader() method, however, will not overwrite an existing header value if a header with the same name already exists. It instead just associates this value with the header as an additional value making the header have multiple values. If the header does not already exist, the addHeader() works just like the setHeader().

1) Create the HeaderTest.java servlet class within the src folder of the web application

package info.icontraining.servlets;

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

public class HeaderTest extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      response.setHeader("h1", "Hello");
      response.addHeader("h1", "Bye");
        
      response.setHeader("h2", "Hello");
      response.addHeader("h2", "Bye");
      response.setHeader("h2", "Hi");

      out.close();
   }
}


2) Configure the servlet in the web.xml file of the web application present in the WebContent/WEB-INF folder

<servlet>
   <servlet-name>headerTest</servlet-name>
   <servlet-class>info.icontraining.servlets.HeaderTest</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>headerTest</servlet-name>
   <url-pattern>/headers</url-pattern>
</servlet-mapping>


3) Test the code by accessing the following URL in the browser. Check the response headers in the screen for the Live HTTP Headers add-on for firefox.

http://localhost:8080/WebAppName/headers

No comments:

Post a Comment