下面的方法抛出:servlet的Servlet.service()DetailCakeServlet引发了异常
java.lang.IllegalStateException: Cannot forward after response has been committed.
码
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
CakeDAO dao = new CakeDAO();
String strID = request.getParameter("id");
int id = Integer.parseInt(strID);
request.setAttribute("cake", dao.getCakeById(id));
request.getRequestDispatcher("/WEB-INF/detail.jsp").forward(request, response);
}catch (Exception ex) {
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
}
但是当我删除资源输出对象时,它可以工作。可能是什么原因 ?
要么在没有输出的情况下进行转发:
try {
CakeDAO dao = new CakeDAO();
String strID = request.getParameter("id");
int id = Integer.parseInt(strID);
request.setAttribute("cake", dao.getCakeById(id));
request.getRequestDispatcher("/WEB-INF/detail.jsp").forward(request, response);
} catch (Exception ex) {
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
}
或做:
try {
CakeDAO dao = new CakeDAO();
String strID = request.getParameter("id");
int id = Integer.parseInt(strID);
PrintWriter out = response.getWriter();
out.println("Cake: " + dao.getCakeById(id)); // Hereafter an exception would err.
// NEVER forward: ... .forward(request, response);
} catch (Exception ex) {
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
}
Try-with-resources自动关闭,不需要。转发时甚至会引发错误。
更重要的是,没有得到作家,你会更好。在实际写入输出(缓冲I / O!)之后,转发是错误的,因此catch中的转发是脏的。
如上所述,here(在规范中没有很快发现),在输入catch块之前,try-with-resources构造将尝试关闭try块内打开的资源 - 即你的out
,从而response
,您尝试在catch
块中重定向时已经关闭。我建议通过以下方式处理可能的异常:
try (PrintWriter out = response.getWriter()) {
try {
CakeDAO dao = new CakeDAO();
String strID = request.getParameter("id");
int id = Integer.parseInt(strID);
request.setAttribute("cake", dao.getCakeById(id));
request.getRequestDispatcher("/WEB-INF/detail.jsp").forward(request, response);
}catch (Exception ex) {
request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
}
}
实际上,我没有在你的代码中看到使用out
,所以整个try-with-resources块只是多余的。