【问题标题】:How to send redirect to error page which Is located under WEB-INF dir from servlet?如何从 servlet 将重定向发送到位于 WEB-INF 目录下的错误页面?
【发布时间】:2021-06-07 15:37:14
【问题描述】:

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

听众:

@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,但我无法访问它。我该如何解决?

【问题讨论】:

    标签: java redirect servlets custom-error-pages


    【解决方案1】:

    我认为你只是使用forward 的getRequestDispatcher :

    示例:

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

    【讨论】:

    • 然而,正确的方法是抛出异常。因此,此答案与其说是解决方案,不如说是一种解决方法。
    猜你喜欢
    • 2012-04-01
    • 2016-07-16
    • 2012-11-17
    • 2016-01-12
    • 1970-01-01
    • 2015-01-04
    • 2012-07-27
    • 1970-01-01
    相关资源
    最近更新 更多