json - Spring MVC jackson 异常处理

标签 json spring spring-mvc

我可以处理 jackson 吗UnrecognizedPropertyException对于 @RequestBody范围?我该如何配置?

我正在做一个 spring MVC 项目,我使用 jackson 作为 json 插件。 json 请求中字段名称的任何拼写错误都会导致错误页面,该页面应该是由错误消息组成的 json 字符串。我是 spring 的新手,我认为这个错误处理可以通过一些 spring 配置来完成,但在多次尝试后失败了。有什么帮助吗?

这是我的 mvc 配置:

@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {     
    @Bean
    public ViewResolver resolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        return bean;
    }    
    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }       
}

我的 Controller :
@RequestMapping(value = "/Login", method = RequestMethod.POST, 
    consumes="application/json", produces = "application/json")
public @ResponseBody AjaxResponse login(
    @RequestBody UserVO user, HttpServletRequest request) {
    //do something ...
}

正常请求json是:
{"Username":"123123", "Password":"s3cret"}

但是如果我发送以下请求:
{"Username":"123123", "pwd":"s3cret"}

哪个字段名称拼写错误,那么 Spring 会捕获这个 UnrecognizedPropertyException ,并返回一个错误页面,但我想捕获此异常并返回一个 json 字符串。我怎样才能做到这一点?

最佳答案

使用@ExceptionHandler 注释。关于它的一些文档:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

@Controller
public class WebMvcConfig {

  @RequestMapping(value = "/Login", method = RequestMethod.POST, 
    consumes="application/json", produces = "application/json")
  public @ResponseBody AjaxResponse login(@RequestBody UserVO user, HttpServletRequest request) {
    //do something ...
  }

  @ExceptionHandler(UnrecognizedPropertyException.class)
  public void errorHandler() {
    // do something. e.g. customize error response
  }
}

关于json - Spring MVC jackson 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27141454/

相关文章:

java - 如何使用 Spring JPA 存储库按多个字段过滤实体?

Spring i18n : problem with multiple property files

spring - REST 服务需要 web.xml 吗?

java - 我的 Java JSON 解析器出了什么问题?

php - 将 SimpleXML 转换为 JSON PHP

java - Spring PropertyPlaceHolder 问题

java - 由于双重上下文 (servlet+ContextLoaderListener),所有 Spring Framework bean 都会重复

java - spring mvc 3.0之后没有改变重定向url

python - Json 文件到 pyspark 数据帧

javascript - Jquery 循环 Json 数组时仅附加最后一个值