Disable all default HTTP error response content in Tomcat

后端 未结 8 1401
感情败类
感情败类 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) {
            }
        }
    }
    

提交回复
热议问题