Arturo Hernandez
Arturo Hernandez

Reputation: 2859

Why would the placement of response.addHeader in a HttpServlet make it fail

I have some code that looks like this:

public class EGOChervonAPIMethods extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        initalization code

        big case statement

        response.addHeader("Access-Control-Allow-Origin", originHeader);
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");
    }

And the headers sometimes get added sometime they do not. I can step through the code and it does execute. Like it should since it is at the very end of the code not if there. And no exceptions triggered. I even checked with a call to response.containsHeader.

If I change this to be:

public class EGOChervonAPIMethods extends HttpServlet
{
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        initalization code

        response.addHeader("Access-Control-Allow-Origin", originHeader);
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");

        big case statement
    }

It works. clearly something happens in the big case statement. But as far as I can see the code is identical. Only a few calls to response.getWriter().println are different.

What else could it be?

Upvotes: 0

Views: 86

Answers (1)

Florian H.
Florian H.

Reputation: 304

I would discourage to write headers after the body. The headers are usually already sent when you write some content in the body (through the writer), so you cannot set other headers.

More details in the answer of HttpServletResponse lose header if write body before addHeader?

Upvotes: 1

Related Questions