处理异常时从Spring返回ModelAndView

时间:2016-03-01 20:15:29

标签: java spring exception-handling servlet-3.0 modelandview

处理spring项目中的异常处理。

我跟着this approach来处理例外情况。

一切都很顺利,但我想返回一个ModelAndView,而不是使用 PrintWriter 对象编写 text / html

以下是我遵循的方法。

ExceptionHandler.java

package com.test.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

/**
 * Servlet implementation class ExceptionHandler
 */
@WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse          response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //response.getWriter().append("Served at: ").append(request.getContextPath());
    //processError(request,response);
    handleException(request,response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //processError(request,response);
    handleException(request,response);
}

//I want this ModelAndView to be returned and should display the page that was set in ModelANdView object.
private ModelAndView handleException(HttpServletRequest request,HttpServletResponse response) throws IOException  {


    ModelAndView model = new ModelAndView("ErrorPage");
    model.addObject("errMsg", "this is Exception.class");

    return model;

}
//I don't want this approach.
/*private void processError(HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Analyze the servlet exception
    Throwable throwable = (Throwable) request
            .getAttribute("javax.servlet.error.exception");
    Integer statusCode = (Integer) request
            .getAttribute("javax.servlet.error.status_code");
    String servletName = (String) request
            .getAttribute("javax.servlet.error.servlet_name");
    if (servletName == null) {
        servletName = "Unknown";
    }
    String requestUri = (String) request
            .getAttribute("javax.servlet.error.request_uri");
    if (requestUri == null) {
        requestUri = "Unknown";
    }

    // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      out.write("<html><head><title>Exception/Error Details</title></head>   <body>");
      if(statusCode != 500){
          out.write("<h3>Error Details</h3>");
          out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
          out.write("<strong>Requested URI</strong>:"+requestUri);
      }else{
          out.write("<h3>Exception Details</h3>");
          out.write("<ul><li>Servlet Name:"+servletName+"</li>");
          out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
          out.write("<li>Requested URI:"+requestUri+"</li>");
          out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
          out.write("</ul>");
      }

      out.write("<br><br>");
      out.write("<a href=\"index.html\">Home Page</a>");
      out.write("</body></html>");
}*/

}

web.xml 中,我添加了以下标记来设置错误位置。

 <error-page>
 <error-code>404</error-code>
 <location>/ExceptionHandler</location>
 </error-page>

编辑:我知道void无法返回ModelAndView对象,但是在URL无效的情况下寻找加载 ErrorPage 的方法

0 个答案:

没有答案