Search code examples
javajsphttptomcathttp-response-codes

My JSP returns a 202 (SC_ACCEPTED) status, but the caller gets a 200 (SC_OK) status


I am accessing a simple JSP page on Tomcat:

<%@ page import = "java.io.Writer" %>
<%
try {
    Writer outWriter = response.getWriter ();
    outWriter.write ("something");
    outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>

But when I test this page with curl, I get a 200 response code instead of the expected 202:

$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Transfer-Encoding: chunked
Date: Mon, 05 Jun 2017 08:09:36 GMT

something

If I remove the content from the response:

<%@ page import = "java.io.Writer" %>
<%
try {
    //Writer outWriter = response.getWriter ();
    //outWriter.write ("something");
    //outWriter.flush ();
    response.setStatus (HttpServletResponse.SC_ACCEPTED);
}
catch (Throwable t) {
  response.sendError (HttpServletResponse.SC_BAD_REQUEST, t.getMessage ());
}%>

I get the desired response code:

$ curl -i "http://localhost:8090/somepath/somefile.jsp"
HTTP/1.1 202 Accepted
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=52......................AD2; Path=/somepath/; HttpOnly
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2
Date: Mon, 05 Jun 2017 08:12:57 GMT

Is there some Tomcat configuration changing the response code?

My actual goal is to simulate responses of some 3rd party web API that is expected to return a 202 response code + some short content string for successful requests.

My server, which would call this API, expects a 202 response. I guess I can change it to accept both 200 and 202 responses, but I wanted my code to match the documentation of the 3rd party API.


Solution

  • Move the setStatus() to the top of the JSP. Look at the compiled JSP to see how the code is written by the compiler. Chances are once Status has been set, it cannot be overridden. The flush() method maybe have set the Status to 200.