Dispatcher不会抛出异常

时间:2011-07-30 22:50:43

标签: java exception forward

当我想转发到不存在的资源时,我想让调度程序抛出异常,这是我的代码

 String page = (String) request.getAttribute("page");  //page to be forwarded form servlet to jsp
    if (page == null) {
        page = request.getParameter("page");//page to be forwarded form jsp to servlet
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/InstitutionPages/" + page + ".jsp");
    try {
        dispatcher.forward(request, response);
    } catch (IOException ex) {
           ex.printStackTrace();
        LogoutServlet.redirectToLoginPage(request, response);
    } catch (javax.servlet.ServletException e) {
           e.printStackTrace();
        Logger.getLogger(RegistrarManagementServlet.class.getName()).log(Level.SEVERE, null, e);
        LogoutServlet.redirectToLoginPage(request, response);
    } catch (java.lang.IllegalArgumentException e) {
        e.printStackTrace();
        LogoutServlet.redirectToLoginPage(request, response);
    }

在页面中,我发送无效页面名称,但在控制台

上发生此错误
SEVERE: PWC6117: File "D:\versions\v30\OnlineQuerySystem_New\build\web\WEB-INF\InstitutionPages\Registerkk.jsp" not found

没有打印任何一个Stack痕迹!

1 个答案:

答案 0 :(得分:1)

以下是您的servlet的外观:

public class SimpleServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // do something at the servlet here

    String page = (String) req.getAttribute("page"); // page to be forwarded
                                                        // form servlet to
                                                        // jsp
    if (page == null) {
        page = req.getParameter("page");// page to be forwarded form jsp to
                                        // servlet
    }

    this.forwardIfExists(req, resp, page);

}

protected void forwardIfExists(HttpServletRequest req,
        HttpServletResponse resp, String page) throws ServletException, IOException {

    File pagePath = new File(this.getServletContext().getRealPath(page));

    if ( pagePath.exists() ) {
        req.getRequestDispatcher( page ).forward(req, resp);
    } else {
        throw new IllegalArgumentException(String.format( "The page %s does not exist", page ));
    }

}

}

另外,不要捕获servlet方法抛出的 ServletException IOException ,如果它们发生了应用程序中发生的非常糟糕的事情,则不应该吞下这些异常因为你在你的代码中。应该保留这些异常,并且容器应该捕获它们。您应该记录它们而不是尝试打印堆栈跟踪,因为这将打印在错误的流中,并且在生产服务器上不可见。