如何将重定向发送到位于 servlet 的 WEB-INF 目录下的错误页面?

How to send redirect to error page which Is located under WEB-INF dir from servlet?

我有 ServletContextListener,我在其中初始化数据库 JNDI 轮询,如果发生异常,我发现我将属性设置为 Servlet 上下文。

听众:

@WebListener
public class ApplicationListener implements ServletContextListener  {
    private static final Logger LOGGER = LogManager.getLogger(ApplicationListener.class);
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext ctx = sce.getServletContext();
        DAOFactory dao = DAOFactory.getDAOFactory(1);
        try {
            MySQLDAOFactory.dataSourceInit();
            QueriesUtil.getQueries();
        } catch (SQLException | NamingException throwables) {
               LOGGER.error(throwables);
               ctx.setAttribute("Error",throwables.getMessage());
        }
        ctx.setAttribute("MySQLFactory",dao);
        Locale.setDefault(new Locale("ua"));
    }
}

前端控制器:

@WebServlet(name = "FrontController", value = "/pages/*")
public class FrontController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext context = getServletContext();
            String error = (String)context.getAttribute("Error");
            if(error!=null){
                resp.sendRedirect(req.getContextPath()+"/WEB-INF/view/error.jsp?errorMessage="+error);
            }
        try {
            View view = new View(req, resp);
            Action action = ActionFactory.getInstance().getAction(req);
            action.execute(view);
            view.navigate();
        } catch (Exception e) {
            resp.sendRedirect(req.getContextPath()+"/WEB-INF/view/error.jsp?errorMessage="+e.getMessage());
        }
    }
}

FrontController 检查 servlet 上下文以找到此属性,如果它存在,我应该将重定向发送到 errorPage,但我无法访问它。我该如何解决?

我想你只是使用 getRequestDispatcherforward :

示例:

this.getServletContext().getRequestDispatcher("/WEB-INF/view/error.jsp?errorMessage="+e.getMessage()).forward( request, response );