在Jetty 9.4.2中禁用默认错误响应正文

用户名

当Jetty捕获异常并返回错误时,如何禁用默认响应正文?我没有使用任何XML或WAR,也不想添加任何XML或WAR。

我宁愿避免try { // Servlet code } catch (Exception e) { resp.setStatus(500) }在每个servlet中都做一个

如果我不这样做,Jetty将返回500响应,并带有指定堆栈跟踪的正文。如果到达未找到的端点,Jetty将返回404响应,并显示“ Powered by Jetty”。我要删除这些正文,只保留响应代码。

这是启动我的Jetty服务器的代码:

private static void startServer() throws Exception {
    final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(7070);
    final WebAppContext context = new WebAppContext("/", "/");
    context.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebInfConfiguration() });
    context.setExtraClasspath("build/classes/main/com/example");
    server.setHandler(context);
    server.start();
    server.join();
}
用户名

Jetty文档中描述了该解决方案

需要类扩展ErrorHandler,以便在生成错误页面时覆盖Jetty默认行为。它可以通过ContextHandler或Jetty服务器进行注册

CustomErrorHandler类:

public class CustomErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException {}
}

然后,将其添加到我的Jetty嵌入式配置中: context.setErrorHandler(new CustomErrorHandler());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章