ResponseBodyAdvice 处理json信息

package com.tianqiauto.advice;

import com.tianqiauto.base.bean.TYuanGong;
import com.tianqiauto.tis.utils.TisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.swagger.web.SwaggerResource;

import java.util.ArrayList;
import java.util.Iterator;

@Slf4j
@RestControllerAdvice
public class SwaggerAdvice implements ResponseBodyAdvice {


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        /**
         * 判断访问地址是否是swagger-resources
         * 是的话判断用户是否登录,没有登录的话,只显示XDD
         */ServletServerHttpRequest request = (ServletServerHttpRequest) serverHttpRequest;
        String path = request.getURI().getPath();
        if (!StringUtils.isEmpty(path) && path.contains("swagger-resources")){
            TYuanGong user = TisUtils.getPcCurrentUser(request.getServletRequest());
            if (user == null){
                if (o instanceof ArrayList){
                    ArrayList<SwaggerResource> arrayList = (ArrayList<SwaggerResource>) o;
                    Iterator<SwaggerResource> iterator = arrayList.iterator();
                    while (iterator.hasNext()){
                        SwaggerResource swaggerResource = iterator.next();
                        if (!"XDD".equals(swaggerResource.getName())){
                            iterator.remove();
                        }
                    }
                }
            }
        }
        return o;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }
}

你可能感兴趣的:(spring)