[英]Servlet exception handling: forwarding to the same error page with different messages
如何在Servlet中使用不同的消息轉發到同一錯誤頁面時處理異常? 在我的servlet中,我具有以下doGet(在此簡化)方法,並帶有切換用例:
public class NewServlet extends HttpServlet {
//[...]
protected void doGet(
//[...]
try {
DAO ldapdao = new DAO();
List<Entry> entries = null;
switch (enumPage.fromString(operation)) {
// [...]
case add:
String values[] = request.getParameterValues("item");
try {
ldapdao.addentry(values);
link = "entryadded.jsp";
} catch (Exception exp) { // 2
throw new MyException("Entry Not Added");
}
break;
case remove:
entries = ldapdao.searchEntry(request.getParameter("item"));
if (entries.isEmpty()) {
throw new MyException("Entry Not Removed"); //3
} else {
ldapdao.remove(request.getParameter("item"));
link = "entryremoved.jsp";
}
break;
case modified:
String values1[] = request.getParameterValues("item");
try {
ldapdao.modify(values1);
link = ("modified.jsp");
} catch (Exception exp) { //4
throw new MyException("Entry Not Modified");
}
// [...]
然后有我的自定義異常:
package com.mycompany.test_servlet;
import javax.servlet.ServletException;
public class MyException extends ServletException {
private String message = null;
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
}
和web.xml文件:
<error-page>
<location>/Error.jsp</location>
</error-page>
嘗試指出異常類型:
<error-page>
<exception-type>com.mycompany.test_servlet.MyException</exception-type>
<location>/Error.jsp</location>
</error-page>
您可以嘗試在請求對象中設置屬性,同時捕獲異常
request.setAttribute("exception", ex.getMessage());
然后在error.jsp中獲取此屬性,例如:
<% if (request.getAttribute("exception") != null) { %>
<tr>
<td colspan='2'><p align=right>Authentication Error (try again):<br>
<%=request.getAttribute("exception")%>
</p></td>
</tr>
<%}%>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.