zha*_*eng 5 spring json spring-mvc
我能对付杰克逊吗 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
@RequestMapping(value = "/Login", method = RequestMethod.POST,
consumes="application/json", produces = "application/json")
public @ResponseBody AjaxResponse login(
@RequestBody UserVO user, HttpServletRequest request) {
//do something ...
}
Run Code Online (Sandbox Code Playgroud)
正常请求json是:
{"Username":"123123", "Password":"s3cret"}
Run Code Online (Sandbox Code Playgroud)
但是如果我发送以下请求:
{"Username":"123123", "pwd":"s3cret"}
Run Code Online (Sandbox Code Playgroud)
哪个字段名称拼写错误,然后 Spring 捕获 thisUnrecognizedPropertyException并返回错误页面,但我想捕获此异常并返回一个 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4498 次 |
| 最近记录: |