Spring MVC Spring安全性和错误处理 [英] Spring MVC Spring Security and Error Handling

查看:153
本文介绍了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.

知道如何处理吗?

推荐答案

原因是

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开始,可以使用

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

设置在找不到此请求的处理程序时是否引发NoHandlerFoundException.然后可以使用HandlerExceptionResolver或@ExceptionHandler控制器方法来捕获此异常.

Set whether to throw a NoHandlerFoundException when no Handler was found for this request. This exception can then be caught with a HandlerExceptionResolver or an @ExceptionHandler controller method.

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安全性和错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆