我在Tomcat上访问一个简单的JSP页面:
<%@ 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 ());
}%>
但是当我用curl
测试此页面时,我得到的是200响应代码,而不是预期的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
如果我从回复中删除了内容:
<%@ 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 ());
}%>
我得到了所需的回复代码:
$ 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
是否有一些Tomcat配置更改了响应代码?
我的实际目标是模拟某些第三方Web API的响应,该API预计会返回202响应代码+一些短内容字符串,用于成功请求。
我的服务器会调用此API,需要202响应。我想我可以将其更改为接受200和202响应,但我希望我的代码与第三方API的文档相匹配。
答案 0 :(得分:1)
将setStatus()移动到JSP的顶部。查看编译后的JSP,了解编译器如何编写代码。机会一旦设置了Status,就无法覆盖。 flush()方法可能已将Status设置为200。