How to send servlet response to web.xml configured error page

后端 未结 2 1465
花落未央
花落未央 2021-01-15 08:46

I am using Tomcat. I defined some in web.xml and mapped 404 error to page /error/error.jsp. I need to

2条回答
  •  伪装坚强ぢ
    2021-01-15 09:49

    Just use HttpServletResponse#sendError() with a status code. E.g.

    File resource = new File(path, name);
    if (!resource.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // Sends 404.
        return;
    }
    

    The servletcontainer will then display the suitable errorpage.

    Note: the return statement isn't there for decoration. It will avoid that the remant of the code in the same method block will continue to run and might produce IllegalStateExceptions in the appserver logs! Starters namely often think that methods like sendRedirect(), forward(), sendError(), etc somehow automagically exits the method block when invoked. This is thus not true ;)

提交回复
热议问题