本文介绍了Spring MVC Spring 安全和错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ResponseEntityExceptionHandler 来全局处理错误并且几乎正常工作,除了我想用 spring 处理错误的请求.通过覆盖 handleNoSuchRequestHandlingMethod 的任何逻辑都应该处理这个问题,但是处理总是得到

I'm using ResponseEntityExceptionHandler for global handling the error and almost working normal, except I want to handle wrong request with spring. By any logic overriding handleNoSuchRequestHandlingMethod should handle this, but insted of handling always get

HTTP 状态 404 -

类型 状态报告

消息

描述 请求的资源不是可用.

description The requested resource is not available.

我刚刚在控制台中启用调试时得到这个:

I just got this when enable debuging in console:

警告:org.springframework.web.servlet.PageNotFound - 未找到带有 URI 的 HTTP 请求的映射

只是通过处理来澄清我的意思是我要返回 JSON.

just to clarify by handling I mean I'm returning JSON.

知道如何处理这个问题吗?

any idea how to handle this?

推荐答案

原因是就在那里,在 DispatcherServlet 类中;它发送错误响应而无需调用异常处理程序(默认情况下).

The reason is right there, in the DispatcherServlet class; it sends error response without bothering to call exception handler (by default).

从 4.0.0.RELEASE 开始,可以使用 throwExceptionIfNoHandlerFound 参数:

Since 4.0.0.RELEASE this behaviour can be simply changed with throwExceptionIfNoHandlerFound parameter:

设置当没有找到此请求的Handler时是否抛出NoHandlerFoundException.然后可以使用 HandlerExceptionResolver 或 @ExceptionHandler 控制器方法捕获此异常.

XML 配置:

<servlet>
    <servlet-name>rest-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

基于Java的配置:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
    ...
}

那么NoHandlerFoundException可以这样处理:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex,
            HttpHeaders headers, HttpStatus status, WebRequest request) {
        // return whatever you want
    }
}

这篇关于Spring MVC Spring 安全和错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:17