1

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

 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

没有打印任何堆栈跟踪!

4

1 回答 1

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 方法抛出的ServletExceptionIOException,如果它们发生了,那么您的应用程序中正在发生一些非常糟糕的事情,并且您不应该像在代码中那样吞下这些异常。这些异常应该保持原样,容器应该捕获它们。您应该记录它们并且不要尝试打印堆栈跟踪,因为这将在错误流中打印,并且在生产服务器上不可见。

于 2011-07-30T22:57:03.630 回答