码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot(五)ResponseBodyAdvice

时间:2018-05-27 13:49:35      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:class   bsp   eth   port   div   import   http   color   and   

因为SpringBoot默认的ResponseBody的处理程序就是HandlerMethodReturnValueHandler,所以我们自己写的HandlerMethodReturnValueHandler通常无法生效,

非要使用HandlerMethodReturnValueHandler,那么只能替换掉默认的,

如果只是想对Controller的所有返回值进行封装,使用ResponseBodyAdvice会更加简单一些,下面几行代码就足够了

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 12614 on 2018/5/11.
 */
@ControllerAdvice
public class TestResponseAdvice implements ResponseBodyAdvice<Object>{
    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(ResponseBody.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        Map<String,Object> res = new HashMap<>();
        res.put("code","1");
        res.put("data",o);
        return res;
    }
}

 

SpringBoot(五)ResponseBodyAdvice

标签:class   bsp   eth   port   div   import   http   color   and   

原文地址:https://www.cnblogs.com/chenss15060100790/p/9095584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!