java - 自定义错误请求HTTP400页面Spring MVC

标签 java spring error-handling bad-request

当错误的请求完成并返回HTTP400错误代码时,是否可以自定义从Spring返回的html页面?

最佳答案

是的,您可以实现这一目标。
您需要定义全局错误处理程序 ControllerAdvice 批注。

示例代码为:

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;

        // setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
}

进一步阅读:
  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html
  • https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
  • 关于java - 自定义错误请求HTTP400页面Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48099718/

    相关文章:

    java - ZeroConf 浏览器中未找到 JmDNS 服务

    java - Java 中集合的并集和交集(生成拓扑)

    php - 在 php for linux 命令中停止错误报告

    go - 将要与 defer 一起使用的方法作为参数传递

    java - 如何在java应用程序中导入com.ms.com.*

    java - 文件路径给出 NullPointer

    java - 在STS上运行Spring项目出现ServletException错误

    java - 捕获Spring数据异常

    spring - Java 嵌入式 jetty 正在接受 HTTP TRACE 方法

    r - 如何停止/结束/停止 R 中的脚本?