y79431861
y79431861
采纳率0%
2018-12-12 10:46

@RestControllerAdvice和@RestController返回不一样的格式

5

springboot版本 2.1.1.RELEASE
ControllerAspect.java代码
@RestControllerAdvice
public class ControllerAspect {

@ExceptionHandler(Exception.class)
public Object dispose(final HttpServletRequest request, final HttpServletResponse response,
        final Exception ex) {

    Map<String,String> map = new HashMap<String,String>();
    map.put("mgs", ex.getMessage());
    map.put("code", "9999");
    return map;

}

}

UserController代码:
@RestController
public class UserController {

@RequestMapping(value = "/test.json", method = { RequestMethod.POST,
        RequestMethod.GET },produces = "application/json")
public Object refreshCache(final HttpServletRequest request, final String token) {
    Map<String,String> map = new HashMap<String,String>();
    map.put("mgs", "success");
    map.put("code", "0000");
    return map;
}

}
正常情况下:访问http://127.0.0.1:8080/test.json返回数据为格式是json
{"code":"0000","mgs":"success"}

在UserController里面抛出异常后
@RestController
public class UserController {

@RequestMapping(value = "/test.json", method = { RequestMethod.POST,
        RequestMethod.GET },produces = "application/json")
public Object refreshCache(final HttpServletRequest request, final String token) {
    Map<String,String> map = new HashMap<String,String>();
    map.put("mgs", "success");
    map.put("code", "0000");
    System.out.println(1/0);
    return map;
}

}
返回xml格式

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • y79431861 y79431861 3年前

    你在pom.xml加上

    <groupId>com.fasterxml.jackson.jaxrs</groupId>
                <artifactId>jackson-jaxrs-xml-provider</artifactId>
            </dependency>
    

    后就是xml了
    @RequestMapping里面配置的application/json不起作用

    点赞 评论 复制链接分享
  • BUGJOB BUGJOB 3年前

    返回的还是json啊

    点赞 评论 复制链接分享

相关推荐