Search code examples
javahttp-redirectservletscustom-error-pages

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


I have ServletContextListener where I initialize database JNDI Poll and If there are exceptions occurs I catch that I set Attribute to Servlet Context.

Listener :

@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"));
    }
}

FrontController :

@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 check servlet context to find this attribute and if It exists I should send redirect to errorPage but I can't access to it. How can I solve it?


Solution

  • I think you just use the forward of getRequestDispatcher :

    Exemple:

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