3

每当发生某些特定问题时,我想exception从 servlet 中抛出一个类似于以下内容的 custom 。

public class CustomException extends Throwable {

    private String[] errArray;

    public CustomException(String[] errArray){
        this.errArray = errArray;
    }

    public String[] getErrors(){
        return errArray;
    }

}

然后,当引发此异常时,我想将用户重定向到特定的错误页面。

<error-page>
    <exception-type>com.example.CustomException</exception-type>
    <location>/WEB-INF/jsp/errorPage.jsp</location>
</error-page>

这是错误页面,我想使用异常隐式对象。

<%@ page isErrorPage="true" %>
<%@ taglib prefix="my" tagdir="/WEB-INF/tags" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

<my:head title="Error"></my:head>
<body>
    <% String errArray = exception.getErrors(); %>
</body>
</html>

现在,当我添加servlet方法CustomException的声明时,就会出现问题。我收到以下错误:throwsdoGet

Exception CustomException is not compatible with throws clause in HttpServlet.doGet(HttpServletRequest, HttpServletResponse)

现在我该如何克服这个问题?甚至可以自定义这样的异常并在抛出它时转发到错误页面?或者还有其他方法吗?提前致谢 :)

4

1 回答 1

4

HttpServletdoGet抛出ServletException如下声明:

    protected void doGet(HttpServletRequest req,
                 HttpServletResponse resp)
          throws ServletException,
                 java.io.IOException

请使您CustomException的扩展ServletException符合方法规范。

编辑:在你的error.jsp中,得到错误:

<% String[] errArray = null; 
  if(exception instanceof CustomException) {
     errArray = (CustomException)exception.getErrors();
  } 
%>

请注意:它返回String[]

于 2012-11-08T05:06:54.467 回答