Disable all default HTTP error response content in

2019-01-16 07:48发布

By default, Tomcat sends some HTML content back to the client if it encounters something like an HTTP 404. I know that via web.xml an <error-page> can be configured to customize this content.

However, I'd just like for Tomcat to not send anything in terms of response content (I'd still like the status code, of course). Is there any way to easily configure this?

I'm trying to avoid A) explicitly sending empty content on the response stream from my Servlet, and B) configuring custom error pages for a whole bunch of HTTP error statuses in my web.xml.

For some background, I'm developing an HTTP API and am controlling my own response content. So for an HTTP 500, for example, I'm populating some XML content on the response containing error information. For situations like an HTTP 404, the HTTP response status is sufficient for clients, and the content tomcat is sending is unnecessary. If there's a different approach, I'm open to hearing it.

Edit: After continued investigation, I still can't find much in the way of a solution. If someone can definitively say this is not possible, or provide a resource with evidence that it will not work, I'll accept that as an answer and try and work around it.

8条回答
Luminary・发光体
2楼-- · 2019-01-16 08:40

As Heikki said, setting the status instead of sendError() causes the Tomcat not touch the response entity/body/payload.

If you only want to send the response headers without any entity, like in my case,

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentLength(0);

does the trick. With Content-Length: 0, the print() will have no effect even if used, like:

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentLength(0);
response.getWriter().print("this string will be ignored due to the above line");

the client receives something like:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 0
Date: Wed, 28 Sep 2011 08:59:49 GMT

If you want to send some error message, use the setContentLength() with message length (other than zero) or you can leave it to the server

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-16 08:43

Although it's Servlet spec compliant, for security reasons I don't want tomcat or any other Servlet container to send error details. I struggled with this as well a bit. After searching and trying, the solution can be summed up as:

  1. as others mentioned, don't use sendError(), use setStatus() instead
  2. frameworks like e.g. Spring Security use sendError() though...
  3. write a Filter that
    a. redirects calls to sendError() to setStatus()
    b. flushes the response at the end to prevent the container from further modifying the response

A little example servlet filter doing this can be found here.

查看更多
登录 后发表回答