如何验证错误类型5xx或4xx的自定义错误屏幕

时间:2017-10-28 05:09:12

标签: servlets java-ee web.xml

我已经通过在web.xml中使用error-page标记为任何http 5xx或4xx错误创建了自定义错误屏幕,但应该最好的方法是验证。我能够验证错误类型401和403,但不知道其他错误。

2 个答案:

答案 0 :(得分:0)

要快速手动测试以查看错误页面是否正常工作,我只需在处理请求的控制器代码中抛出运行时异常,例如:

throw new RuntimeException("test");

答案 1 :(得分:0)

一个非常简单的servlet怎么样:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/testResponse")
public class TestResponseServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {

        String returnCode = request.getParameter("returnCode");

        if( returnCode == null ) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing returnCode parameter");
            return;
        }

        response.sendError(Integer.parseInt(returnCode), "returned code " + returnCode );
    }
}

http://localhost:8080/testResponse?returnCode=505

之类的方式调用它