欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring中ResponseBodyAdvice的使用详解

程序员文章站 2022-06-25 22:15:14
目录1 responsebodyadvice的简介2 responsebodyadvice的使用1 准备一个springboot项目环境3 添加一个返回包装类4 添加控制类5 接口测试response...

responsebodyadvice可以在注解@responsebody将返回值处理成相应格式之前操作返回值。实现这个接口即可完成相应操作。可用于对response 数据的一些统一封装或者加密等操作

1 responsebodyadvice的简介

responsebodyadvice接口和之前记录的requestbodyadvice接口类似, requestbodyadvice是请求到controller之前拦截,做相应的处理操作, 而responsebodyadvice是对controller返回的{@code @responsebody}or a {@code responseentity} 后,{@code httpmessageconverter} 类型转换之前拦截, 进行相应的处理操作后,再将结果返回给客户端.

responsebodyadvice的源代码:

/**   数据的处理顺序向下
 * allows customizing the response after the execution of an {@code @responsebody}
 * or a {@code responseentity} controller method but before the body is written
 * with an {@code httpmessageconverter}.
 *
 * <p>implementations may be registered directly with
 * {@code requestmappinghandleradapter} and {@code exceptionhandlerexceptionresolver}
 * or more likely annotated with {@code @controlleradvice} in which case they
 * will be auto-detected by both.
 *
 * @author rossen stoyanchev
 * @since 4.1
 * @param <t> the body type
 */
public interface responsebodyadvice<t> {

	/**
	 * whether this component supports the given controller method return type
	 * and the selected {@code httpmessageconverter} type.
	 * @param returntype the return type   方法返回的类型
	 * @param convertertype the selected converter type   参数类型装换
	 * @return {@code true} if {@link #beforebodywrite} should be invoked;
	 * {@code false} otherwise
	 * 返回 true 则下面 beforebodywrite方法被调用, 否则就不调用下述方法
	 */
	boolean supports(methodparameter returntype, class<? extends httpmessageconverter<?>> convertertype);

	/**
	 * invoked after an {@code httpmessageconverter} is selected and just before
	 * its write method is invoked.
	 * @param body the body to be written
	 * @param returntype the return type of the controller method
	 * @param selectedcontenttype the content type selected through content negotiation
	 * @param selectedconvertertype the converter type selected to write to the response
	 * @param request the current request
	 * @param response the current response
	 * @return the body that was passed in or a modified (possibly new) instance
	 */
	@nullable
	t beforebodywrite(@nullable t body, methodparameter returntype, mediatype selectedcontenttype,
			class<? extends httpmessageconverter<?>> selectedconvertertype,
			serverhttprequest request, serverhttpresponse response);

}

说明:

  • supports方法: 判断是否要执行beforebodywrite方法,true为执行,false不执行. 通过该方法可以选择哪些类或那些方法的response要进行处理, 其他的不进行处理.
  • beforebodywrite方法: 对response方法进行具体操作处理

{@code @responsebody} 返回响应体, 例如list集合

{@code responseentity} 返回响应实体对象,例如user对象

2 responsebodyadvice的使用

1 准备一个springboot项目环境

2 添加一个响应拦截类

@controlleradvice
public class baseresponsebodyadvice implements responsebodyadvice<object> {


    @override
    public boolean supports(methodparameter returntype, class convertertype) {
        return true;
    }

    @override
    public object beforebodywrite(object body, methodparameter returntype,
            mediatype selectedcontenttype, class selectedconvertertype, serverhttprequest request,
            serverhttpresponse response) {

        // 遇到feign接口之类的请求, 不应该再次包装,应该直接返回
        // 上述问题的解决方案: 可以在feign拦截器中,给feign请求头中添加一个标识字段, 表示是feign请求
        // 在此处拦截到feign标识字段, 则直接放行 返回body.

        system.out.println("响应拦截成功");

        if (body instanceof baseresponse) {
            return body;
        } else if (body == null) {
            return baseresponse.ok();
        } else {
            return baseresponse.ok(body);
        }
    }
}

3 添加一个返回包装类

@data
@allargsconstructor
@noargsconstructor
public class baseresponse<t> {

    private t data;
    private int status = 200;
    private string message;
    private long srvtime = system.currenttimemillis();

    public baseresponse(string message) {
        this.message = message;
    }

    public baseresponse<t> setdata(t data) {
        this.data = data;
        return this;
    }

    public static <t> baseresponse<t> ok() {
        return new baseresponse<>("操作成功");
    }

    public static <t> baseresponse<t> ok(t data) {
        return new baseresponse<t>("操作成功").setdata(data);
    }

}

4 添加控制类

@controller
@requestmapping("/hello")
public class helloworld {

    // 此处数据从数据库中查询, 案例中也可以使用伪数据代替
    @autowired
    private usermapper usermapper;

    // {@code responseentity} 案列
    @getmapping("/one")
    @responsebody
    public user one() {

        list<user> users = usermapper.selectall();
        system.out.println(users.get(0));
        return users.get(0);
    }

    
    // {@code @responsebody}  案列
    @getmapping("/list")
    @responsebody
    public list<user> list() {

        list<user> users = usermapper.selectall();
        system.out.println(users);
        return users;
    }
}    

5 接口测试

浏览器访问: http://localhost:8080/hello/one

user(id=1, username=李子柒, phone=77777, icon=李子柒的头像, querytime=wed oct 27 20:47:02 cst 2021)
响应拦截成功

浏览器访问: http://localhost:8080/hello/list

[user(id=1, username=李子柒, phone=77777, icon=李子柒的头像, querytime=wed oct 27 20:46:58 cst 2021)]
响应拦截成功

ps: 如果直接响应字符串返回,则会报类型转换异常.

到此这篇关于spring中responsebodyadvice的使用的文章就介绍到这了,更多相关spring中responsebodyadvice使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!