Disable all default HTTP error response content in Tomcat

后端 未结 8 1311
感情败类
感情败类 2020-11-30 22:20

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

相关标签:
8条回答
  • 2020-11-30 23:00

    The quick, slightly dirty, but easy way of stopping Tomcat from sending any error body is to call setErrorReportValveClass against the tomcat host, with a custom error report valve which overrides report to do nothing. ie:

    public class SecureErrorReportValve extends ErrorReportValve {
    
    @Override
    protected void report(Request request,Response response,Throwable throwable) {
    }
    
    }
    

    and set it with:

      ((StandardHost) tomcat.getHost()).setErrorReportValveClass(yourErrorValveClassName);
    

    If you want to send your message, and just think Tomcat shouldn't mess with it, you want something along the lines of:

    @Override
    protected void report(final Request request, final Response response, final Throwable throwable) {
        String message = response.getMessage();
        if (message != null) {
            try {
                response.getWriter().print(message);
                response.finishResponse();
            } catch (IOException e) {
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 23:00

    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

    0 讨论(0)
提交回复
热议问题