使用ResponseBodyAdvice实现下载注解

1、首先定义注解DownloadAble


@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DownloadAble {
}

2、实现ResponseBodyAdvice接口

需要重写beforeBodyWrite()方法和support()方法:
support()方法进行拦截判断,判断是否有下载注解;
beforeBodyWrite()方法实现拦截之后的具体操作,此处实现具体的下载功能,可以从request中获取具体的请求参数。

@ControllerAdvice
public class DownloadResponseBodyAdvice implements ResponseBodyAdvice {

 //实现下载操作
    @Override
    public DownloadResult beforeBodyWrite(DownloadResult result, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                          ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
                                          }
   //判断是否有DownloadAble注解进行拦截
   @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        DownloadAble methodAnnotation = methodParameter.getMethodAnnotation(DownloadAble.class);
        if (methodAnnotation == null) {
            return false;
        }
        return true;
    }

3、测试注解

    @DownloadAble
    @RequestMapping(value = "/testDownload",  method = RequestMethod.GET)
    @ApiOperation(value = "测试下载注解", notes = "测试下载注解", httpMethod = "GET")
    public DownloadResult testDownload(
            @RequestParam(value = "downloadType", required = false) String downloadType,
            @RequestParam(value = "interval", required = false) String interval){
        DownloadResult downloadResult  = new DownloadResult();
        //文件名
        String downloadName = "down";
        //文件列表
        List rows = new ArrayList();
        rows.add("D:\\rsdata\\product.3c\\OMI.O3.L2\\2019\\201908\\20190822\\O3_AURA_OMI_20190822000000_D01.png");
        rows.add("D:\\rsdata\\product.3c\\OMI.O3.L2\\2019\\201908\\20190822\\O3_AURA_OMI_20190822000000_D02.png");
        rows.add("D:\\rsdata\\product.3c\\OMI.O3.L2\\2019\\201908\\20190826\\O3_AURA_OMI_20190826000000_D01.png");
        downloadResult.setDownloadName(downloadName);
        downloadResult.setRows(rows);
        return downloadResult;
    }

下一节研究@ControllerAdvice的使用场景

你可能感兴趣的:(使用ResponseBodyAdvice实现下载注解)