除了使用web.xml的錯誤頁面,您可以使用servlet過濾器。 servlet過濾器可用於捕獲所有異常,或者僅用於特定的異常,如org.springframework.web.portlet.NoHandlerFoundException。 (難道這就是你的意思「處理程序沒有發現」異常?)
過濾器會是這個樣子:
package com.example;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.web.portlet.NoHandlerFoundException;
public class ErrorHandlingFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
// Or you could catch Exception, Error, Throwable...
// You probably want to add exception logging code here.
// Putting the exception into request scope so it can be used by the error handling page
request.setAttribute("exception", e);
// You probably want to add exception logging code here.
request.getRequestDispatcher("/WEB-INF/view/servlet-exception.vm").forward(request, response);
}
}
}
然後,在Spring的DelegatingFilterProxy的的幫助下web.xml中進行設置:
<filter>
<filter-name>errorHandlingFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>errorHandlingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
然後終於,打開過濾器進入一個Spring bean的Spring上下文XML中:
<bean id="errorHandlingFilter" class="com.example.ErrorHandlingFilter" />
您可能需要嘗試過濾器鏈中過濾器的順序,以便失敗的請求仍然通過您提到的其他過濾器。如果您遇到麻煩,一個變化會是做一個HTTP重定向,而不是正,像這樣:
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
request.getSession().setAttribute("exception", e);
response.sendRedirect("/servlet-exception.vm");
}
這將迫使瀏覽器請求您的錯誤處理頁面作爲一個新的HTTP請求,這可能會更容易確保首先通過所有正確的過濾器。如果你需要原始的異常對象,那麼你可以把它放在會話中而不是請求中。
感謝您的回覆....我會嘗試這一點,並更新在這裏。 – 2012-02-08 11:07:28
@ArunPJohny你好,有任何更新? – 2013-03-01 17:27:57