调度程序不会抛出异常 [英] Dispatcher doesn't throw an exception
问题描述
我想让调度员在转发到不存在的资源时抛出异常,这里是我的代码
I want to make the dispatcher throws an exception when I want to forward to non-existing resource, here's my code
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);
}
在页面中,我发送无效的页面名称,但此错误发生在控制台
in page, I send invalid page name, but this error occurs on console
SEVERE: PWC6117: File "D:\versions\v30\OnlineQuerySystem_New\build\web\WEB-INF\InstitutionPages\Registerkk.jsp" not found
没有打印任何一个堆栈跟踪! / p>
No one of Stack traces is printed !
推荐答案
这是您的servlet可以如下所示:
Here's how your servlet could look like:
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 ,如果它们发生在你的应用程序中发生了很糟糕的事情,你不应该把这些异常作为你在你的代码这些例外应该保持原样,容器应该抓住它们。您应该记录它们,而不是尝试打印堆栈跟踪,因为这将在错误流中打印,并且在生产服务器上将不可见。
Also, do not catch the ServletException or IOException thrown by the servlet methods, if they happened something really bad is happening in your application and you should not swallow these exceptions as you are in your code. These exceptions should be be left as they are and the container should catch them. You should log them and not try to print the stack traces, as this is going to print at the err stream and will not be visible at a production server.
这篇关于调度程序不会抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!