tomcat自定义400错误页面

原文链接:https://aspiresoftware.in/blog/catalinatomcat-custom-error-report-valve-to-handle-errors-exceptions/

通过在server.xml文件中 增加上面代码 重启tomcat 400页面如下

tomcat自定义400错误页面_第1张图片

自定义 400 错误页面方法

1.添加依赖


  org.apache.tomcat
  tomcat-catalina
  ${tomcat.version}


  org.apache.tomcat
  tomcat-coyote
  ${tomcat.version}


  org.apache.tomcat
  tomcat-el-api
  ${tomcat.version}


  org.apache.tomcat
  tomcat-jaspic-api
  ${tomcat.version}


  org.apache.tomcat
  tomcat-juli
  ${tomcat.version}


  org.apache.tomcat
  tomcat-servlet-api
  ${tomcat.version}


  org.apache.tomcat
  tomcat-util
  ${tomcat.version}


  org.apache.tomcat
  tomcat-util-scan
  ${tomcat.version}

2 创建类并继承 ErrorReportValve

public class CustomErrorReportValve extends ErrorReportValve

实现方法

@Override protected void report(Request request, Response response, Throwable t)

if (response.getStatus() == 400) {
 StringBuilder sb = new StringBuilder(); 
 //Give relative path of html
 String pageString = getHtmlPage("./400.html");
 response.setContentType("text/html");
 response.setCharacterEncoding("utf-8");
 sb.append(pageString);
 Writer writer = response.getReporter();
  if (writer != null) {
    writer.write(sb.toString());
  }
}

public String getHtmlPage(String path) throws IOException {
    File file = new File("test");
    file.exists();
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
      String line = br.readLine();
      while (line != null) {
        sb.append(line);
        sb.append(System.getProperty("line.separator"));
        line = br.readLine();
      }
    } finally {
      br.close();
    }
    return sb.toString();
  }

你可能感兴趣的:(java,tomcat,servlet,java,分布式,服务器)