spring boot 自定义注解过滤返回字段

1、在spring boot启动类加上  (这里不加貌似也可以生效)

@Import(value = { ApplicationConfig.class })

 2、ApplicationConfig

package com.cnpc.epai.productionmanager.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

@Configuration
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {// 生效
    @Bean
    public JsonReturnHandler jsonReturnHandler() {
        return new JsonReturnHandler();// 初始化json过滤器
    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
        returnValueHandlers.add(jsonReturnHandler());

    }
}

3、JsonFieldFilter 自定义拦截接口定义

package com.cnpc.epai.productionmanager.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonFieldFilter {
    Class<?> type();// 对哪个类的属性进行过滤

    String include() default "";// 包含哪些字段,即哪些字段可以显示

    String exclude() default "";// 不包含哪些字段,即哪些字段不可以显示
}

4、JsonFilterSerializer

package com.cnpc.epai.productionmanager.configuration;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

public class JsonFilterSerializer {
    private static final String DYNC_INCLUDE = "DYNC_INCLUDE";// 包含的标识
    private static final String DYNC_EXCLUDE = "DYNC_EXCLUDE";// 过滤的标识
    private ObjectMapper mapper = new ObjectMapper();

    @JsonFilter(DYNC_EXCLUDE)
    interface DynamicExclude {
    }

    @JsonFilter(DYNC_INCLUDE)
    interface DynamicInclude {
    }

    public void filter(Class<?> clazz, String include, String exclude) {
        if (clazz == null)
            return;
        if (include != null && include.length() > 0) {
            // 包含的操作
            mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_INCLUDE, SimpleBeanPropertyFilter.filterOutAllExcept(include.split(","))));
            // 多个字段用,分割开
            mapper.addMixIn(clazz, DynamicInclude.class);
//            if (clazz.getSuperclass()!=null){
//                mapper.addMixIn(clazz.getSuperclass(), DynamicInclude.class);
//            }
        } else if (exclude != null && exclude.length() > 0) {
            mapper.setFilterProvider(new SimpleFilterProvider().addFilter(DYNC_EXCLUDE, SimpleBeanPropertyFilter.serializeAllExcept(exclude.split(","))));
            mapper.addMixIn(clazz, DynamicExclude.class);
//            if (clazz.getSuperclass()!=null){
//                mapper.addMixIn(clazz.getSuperclass(), DynamicInclude.class);
//            }
        }
    }
    public String toJson(Object object) throws JsonProcessingException {
        return mapper.writeValueAsString(object);
    }
}

5、JsonReturnHandler

package com.cnpc.epai.productionmanager.configuration;


import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;


public class JsonReturnHandler implements HandlerMethodReturnValueHandler {
    @Override
    public void handleReturnValue(Object returnObject, MethodParameter paramter, ModelAndViewContainer container, NativeWebRequest request) throws Exception {
        container.setRequestHandled(true);
        JsonFilterSerializer serializer = new JsonFilterSerializer();
        if (paramter.hasMethodAnnotation(JsonFieldFilter.class)) {// 如果有JsonFieldFilter注解,则过滤返回的对象returnObject
            JsonFieldFilter jsonFilter = paramter.getMethodAnnotation(JsonFieldFilter.class);
            serializer.filter(jsonFilter.type() == null ? returnObject.getClass() : jsonFilter.type(), jsonFilter.include(), jsonFilter.exclude());// 调用过滤方法
        }
        HttpServletResponse response = request.getNativeResponse(HttpServletResponse.class);
        assert response != null;
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(serializer.toJson(returnObject));
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return methodParameter.hasMethodAnnotation(JsonFieldFilter.class);
    }
}

 6、controller如下:

<1>在接口上添加注解及返回字段
@JsonFieldFilter(type = CmsNotify.class, include = "notifyId,notificationTitle,publisher,pubtime")
<2>注意点:

用@Controller 替代 @RestController;

在不需要过滤字段 @JsonFieldFilter(type = ***.class, include = "***")的接口上面使用@ResponseBody注解,但是在需要 过   滤字段的接口上一定不要用@ResponseBody注解,否则过滤失效。

@ApiOperation(value = "获取消息", notes = "获取消息", code = 200, produces = "application/json")
    @GetMapping("/getNotifys")
    @MyOpreatorLog(desc = "getNotifys", menuName = "消息管理-获取消息", operatorType = OperatorTypeConstant.SELECT)
    @JsonFieldFilter(type = CmsNotify.class, include = "notifyId,notificationTitle,publisher,pubtime")
    public PageInfo<CmsNotify> getNotifys(
                                          @ApiParam(name = "page",value = "页码") @RequestParam(name = "page",required = true)Integer page,
                                          @ApiParam(name = "size",value = "每页显示条数") @RequestParam(name = "size",required = true)Integer size) throws IOException {
        return cmsNotifyService.getNotifys(page,size);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值