Slick
Slick

Reputation: 850

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?

Upvotes: 30

Views: 27678

Answers (3)

Abhijit Kalta
Abhijit Kalta

Reputation: 79

Both setHeader() and addHeader() will add a header and value to the response if the header is not already in the response. The difference between set and add shows up when the header is there. In that case: setHeader() overwrites the existing value, whereas addHeader() adds an additional value.

Upvotes: 7

Brian Roach
Brian Roach

Reputation: 76898

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.

Upvotes: 17

csupnig
csupnig

Reputation: 3377

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.

Upvotes: 34

Related Questions