Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring MVC-动态错误处理页面_Java_Spring_Spring Mvc_Error Handling - Fatal编程技术网

Java Spring MVC-动态错误处理页面

Java Spring MVC-动态错误处理页面,java,spring,spring-mvc,error-handling,Java,Spring,Spring Mvc,Error Handling,是否有一种方法可以处理所有可能的错误代码,同时仍将代码传递给my.jsp?在这里,我有一个错误页面通过404,它被添加到模型中。有没有更好的方法来捕获错误并将代码传递给controller/jsp文件,而不是为每个可能的错误代码添加一个错误页面 控制器 @RequestMapping(value="/error/{code}", method=RequestMethod.GET) public String error(@PathVariable("code") String code,

是否有一种方法可以处理所有可能的错误代码,同时仍将代码传递给my.jsp?在这里,我有一个错误页面通过404,它被添加到模型中。有没有更好的方法来捕获错误并将代码传递给controller/jsp文件,而不是为每个可能的错误代码添加一个错误页面

控制器

@RequestMapping(value="/error/{code}", method=RequestMethod.GET)
    public String error(@PathVariable("code") String code, Model model)
    {
        model.addAttribute("code", code);
        return "error";
    }
web.xml

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

404
/错误/404

您可以在Spring中注册一个通用异常解析器来捕获所有异常,并将其转换为
error.jsp
的呈现

使用业务逻辑引发的特殊运行时异常,该异常具有
code
成员:

public class MyException extends RuntimeException {
    private final Integer errorCode;

    public MyException(String message, Throwable cause, int errorCode) {
        super(message, cause);
        this.errorCode = errorCode;
    }
}
或者使用异常消息中的
code
依赖现有的RuntimeException实例

提取
代码
和/或消息,并相应地设置HttpServletResponse状态和ModelAndView

例如:

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
public class GenericHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        ModelAndView mav = new ModelAndView("error");

        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            String code = myException.getCode();

            // could set the HTTP Status code
            response.setStatus(HttpServletResponse.XXX);

            // and add to the model
            mav.addObject("code", code);
        } // catch other Exception types and convert into your error page if required

        return mav;
    }
}