Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Servlet response methods addHeader and setHeader?

Can I use setHeader to set an new header?
Or Do I need to addHeader first, then use setHeader method?

like image 509
Slick Avatar asked Apr 14 '11 07:04

Slick


People also ask

What is response addHeader?

The AddHeader method adds a new HTML header and value to the response sent to the client. It does not replace an existing header of the same name. After a header has been added, it cannot be removed.

What does addHeader do in Java?

addHeader(String name, String value) method adds a MimeHeader object with the specified name and value to this MimeHeaders object's list of headers.

What is the HttpServletResponse?

public abstract interface HttpServletResponse extends ServletResponse. Defines an HTTP servlet response that a servlet running on a Web server sends to a client using HTTP. This interface allows the servlet's service method to access HTTP headers and return data to its client.


2 Answers

The documentation says that you can add multiple values to a particular header using the addHeader method, whereas an initial value would be overwritten if you use the setHeader method.

In both cases a non-existent header would be created.

like image 118
csupnig Avatar answered Oct 07 '22 17:10

csupnig


Javadocs are your friend:

void addHeader(String name, String value) 

Adds a response header with the given name and value. This method allows response headers to have multiple values.

void setHeader(String name, String value) 

Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

like image 25
Brian Roach Avatar answered Oct 07 '22 17:10

Brian Roach