如果您不想tomcat显示错误页面,则不要使用sendError(…)。而是使用setStatus(…)。
例如,如果您想给出405响应,那么您可以
response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
response.getWriter().println("The method " + request.getmethod() +
" is not supported by this service.");
还请记住不要从servlet抛出任何异常。而是捕获Exception,然后再次设置自己的statusCode。
即
protected void service(HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
// servlet code here, e.g. super.service(request, response);
} catch (Exception e) {
// log the error with a timestamp, show the timestamp to the user
long Now = System.currentTimeMillis();
log("Exception " + Now, e);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().println("Guru meditation: " + Now);
}
}
当然,如果您不想要任何内容??,则只需不向写者写任何东西,只需设置状态即可。