2017-04-01 28 views
1

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

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

如果我不这样做,Jetty将返回一个500响应,指定堆栈跟踪的主体。如果找不到端点,则Jetty将返回一个404响应,并带有“由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(); 
} 

回答

-1

将溶液在Jetty documentation描述:

是需要的,以便产生误差页面时覆盖码头默认行为延伸ErrorHandler的类。它可以通过ContextHandler或Jetty服务器注册。

CustomErrorHandler类:

public class CustomErrorHandler extends ErrorHandler { 

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

我加入这个到我的码头嵌入式配置: context.setErrorHandler(new CustomErrorHandler());

我没有使用任何XML或WAR神器
1

在你的WAR文件的WEB-INF/web.xml,指定要用于处理错误的<error-page>元素。

实施例:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
     version="3.1"> 
    <servlet> 
    <servlet-name>myerror</servlet-name> 
    <servlet-class>com.company.MyErrorServlet</servlet-class> 
    </servlet> 

    <servlet-mapping> 
    <servlet-name>myerror</servlet-name> 
    <url-pattern>/myerror</url-pattern> 
    </servlet-mapping> 

    <error-page> 
    <location>/myerror</location> 
    </error-page> 
</web-app> 

<error-page>元件可以是相当强大。

查看其它答案在https://stackoverflow.com/a/16340504/775715

+0

,只是注解的servlet。有没有程序化的解决方案?在你的解决方案中,每个错误(500,404等)都会转到同一个MyErrorServlet吗?我想返回相同的错误代码,但没有泄露数据的Jetty响应主体。 – niklabaz

+0

您使用“WebAppContext”这一事实意味着您正在使用战争(可能是爆炸目录)。你不能用注释指定错误页面(没有注释),你必须使用'WEB-INF/web.xml'。查看其他答案以了解错误分派和有关错误状态的属性。 –