SpringBoot中的内容协商器图解

作者:操作系统

SpringBoot中的内容协商器图解,springboot协商

背景

采用了restful的伴儿对于导出那几个须求本能正是拒绝的~破坏了restful的url的一致性【严酷改进不是http json正是restful 相当多友人都会呢暴流露贰个json就向来称为restful 】

正如上文的代码生成器 大家会批量生成一群代码 在这之中绝大部分都以RestController

  public abstract class AbstractRestController<V extends Vo, S extends So, PK extends Serializable> {
    protected Class<V> voClazz;
    @Autowired
    private Service<V, S, PK> service;
    public AbstractRestController() {
      TypeToken<V> voType = new TypeToken<V>(getClass()) {
      };
      voClazz = (Class<V>) voType.getRawType();
    }
    @PostMapping()
    @ApiOperation(value = "新建实体", notes = "")
    public Result add(@RequestBody V vo) {
      service.saveSelective(vo);
      return ResultGenerator.genSuccessResult();
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除实体", notes = "")
    public Result delete(@PathVariable PK id) {
      service.deleteById(id);
      return ResultGenerator.genSuccessResult();
    }
    @PutMapping
    @ApiOperation(value = "更新实体", notes = "")
    public Result update(@RequestBody V vo) {
      service.updateByPrimaryKeySelective(vo);
      return ResultGenerator.genSuccessResult();
    }
    @GetMapping
    @ApiOperation(value = "获取实体列表", notes = "")
    public Result list(S so) {
      PageHelper.startPage(so.getCurrentPage(), so.getPageSize());
      List<V> list = service.findAll();
      PageInfo pageInfo = new PageInfo(list);
      excelExportParam();
      return ResultGenerator.genSuccessResult(pageInfo);
    }
    protected void excelExportParam() {
      ExportParams ep = new ExportParams(null, "数据");
      ExcelExportParam<V> param = new ExcelExportParam<>();
      param.setClazz(voClazz);
      param.setExcelExport(ExcelExport.NormalExcel);
      param.setExportParams(ep);
      param.setFileName("文件.xls");
      F6Static.setExcelExportParam(param);
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个实体", notes = "")
    public Result detail(@PathVariable PK id) {
      V vo = service.findById(id);
      return ResultGenerator.genSuccessResult(vo);
    }
    @DeleteMapping("/batch")
    @ApiOperation(value = "批量删除实体", notes = "")
    public Result batchDelete(@RequestParam String ids) {
      service.deleteByIds(ids);
      return ResultGenerator.genSuccessResult();
    }
    @GetMapping("/batch")
    @ApiOperation(value = "批量获取实体", notes = "")
    public Result batchDetail(@RequestParam String ids) {
      List<V> vos = service.findByIds(ids);
      return ResultGenerator.genSuccessResult(vos);
    }
    @PostMapping("/batch")
    @ApiOperation(value = "批量新建实体", notes = "")
    public Result add(@RequestBody List<V> vos) {
      service.save(vos);
      return ResultGenerator.genSuccessResult();
    }
    @GetMapping("/count")
    @ApiOperation(value = "获取实体数目", notes = "")
    public Result count(@RequestBody V v) {
      int count = service.selectCount(v);
      return ResultGenerator.genSuccessResult(count);
    }

那么导出如何做啊?【其实能够领略成导出正是多少的展现可是那时结果不是json而已】

抛出一个标题那么登陆登出呢?守旧的方案都以login logout 那么换来restful能源的笔触是吗呢?

唤醒: 登录就是session的新建 登出正是session的删除

实现

依据上述思路 我们自然就想开了那么我们只须求对同四个url再次来到种种结出不就OK了?【pdf一个本子 json三个本子 xml二个本子 xls叁个版本】

bingo!这些是内容协商器的原因

剧情协商器并非Spring创设出来的 事实上这么些从http头里面也能见到

图片 1

1.举例给印度语印尼语客户再次回到斯洛伐克语页面 过于客户再次来到中文页面

HTTP 公约中定义了品质值(简称 q 值),允许客商端为每个偏疼项目列出两种选项,并为种种偏心选项事关二个初期次序。

Accept-Language: en;q=0.5, fr;q=0.0, nl;q=1.0, tr;q=0.0

里头 q 值的界定从 0.0 ~ 1.0(0.0 是优先级最低的,而 1.0 是优先级最高的)。

在乎,偏幸的排列顺序并不重要,独有与偏幸相关的 q 值才是器重的

2.那么还只怕有另外的一部分参数 举例 accept-header

普普通通是先内容协商器有如下二种方案

1.使用Accept header:

这一种为教材中不以为奇描述的一种,理想中这种艺术也是最佳的,但假诺您的能源要给用户一直通过浏览器访问(即html表现),那么由于浏览器的差别,发送上来的Accept Header头将是不雷同的. 将促成服务器不知要回去什么格式的数量给你. 上面是浏览器的Accept Header   

 chrome: 
    Accept:application/xml,application/xhtml+xml,textml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5     
    firefox:
    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8      
    IE8: 
    Accept:image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*  

2.用到扩充名

痛失了同一url多样表现的点子,但前几日这种在其实条件中是应用最多的.因为特别契合程序猿的审雅观.

比如/user.json /user.xls /user.xml

动用参数 以后游人如织open API是行使这种方法,比方天猫

只是对于不一样浏览器也许accept-header并不是专程统一 因而不菲落实选择了2 3二种方案

小编们在Spring中动用上述三种方案

率先配置内容协商器

代码

@Bean
  public ViewResolver contentNegotiatingViewResolver(
      ContentNegotiationManager manager) {
    // Define the view resolvers
    ViewResolver beanNameViewResolver = new BeanNameViewResolver();
    List<ViewResolver> resolvers = Lists.newArrayList(beanNameViewResolver);
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setViewResolvers(resolvers);
    resolver.setContentNegotiationManager(manager);
    return resolver;
  }
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(true)
        .useJaf(false)
        .favorParameter(true)
        .parameterName("format")
        .ignoreAcceptHeader(true)
        .defaultContentType(MediaType.APPLICATION_JSON)
        .mediaType("json", MediaType.APPLICATION_JSON)
        .mediaType("xls", EXCEL_MEDIA_TYPE);
  }

创制对应的调换器

  private HttpMessageConverter<Object> createExcelHttpMessageConverter() {
    ExcelHttpMessageConverter excelHttpMessageConverter = new ExcelHttpMessageConverter();
    return excelHttpMessageConverter;
  }

直接使用easy-poi导出数据

  /*
   * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
   * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
   * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
   * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
   * Vestibulum commodo. Ut rhoncus gravida arcu.
   */
  package com.f6car.base.web.converter;
  import cn.afterturn.easypoi.excel.ExcelExportUtil;
  import com.f6car.base.common.Result;
  import com.f6car.base.core.ExcelExport;
  import com.f6car.base.core.ExcelExportParam;
  import com.github.pagehelper.PageInfo;
  import com.google.common.collect.Lists;
  import org.apache.poi.ss.usermodel.Workbook;
  import org.springframework.http.HttpHeaders;
  import org.springframework.http.HttpInputMessage;
  import org.springframework.http.HttpOutputMessage;
  import org.springframework.http.MediaType;
  import org.springframework.http.converter.AbstractHttpMessageConverter;
  import org.springframework.http.converter.GenericHttpMessageConverter;
  import org.springframework.http.converter.HttpMessageNotReadableException;
  import org.springframework.http.converter.HttpMessageNotWritableException;
  import java.io.IOException;
  import java.lang.reflect.Type;
  import java.net.URLEncoder;
  import java.util.Collection;
  import java.util.Collections;
  import java.util.Map;
  import static com.f6car.base.core.F6Static.getExcelExportParam;
  /**
   * @author qixiaobo
   */
  public class ExcelHttpMessageConverter extends AbstractHttpMessageConverter<Object>
      implements GenericHttpMessageConverter<Object> {
    public static final MediaType EXCEL_MEDIA_TYPE = new MediaType("application", "vnd.ms-excel");
    public ExcelHttpMessageConverter() {
      super(EXCEL_MEDIA_TYPE);
    }
    @Override
    protected boolean supports(Class<?> clazz) {
      return false;
    }
    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
      return null;
    }
    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
      HttpHeaders headers = outputMessage.getHeaders();
      Collection data = getActualData((Result) o);
      ExcelExportParam excelExportParam = getExcelExportParam();
      Workbook workbook;
      switch (excelExportParam.getExcelExport()) {
        case NormalExcel:
          workbook = ExcelExportUtil.exportExcel(
              excelExportParam.getExportParams(),
              (Class<?>) excelExportParam.getClazz(),
              (Collection<?>) data);
          break;
        case MapExcel:
          workbook = ExcelExportUtil.exportExcel(
              excelExportParam.getExportParams(),
              excelExportParam.getExcelExportEntities(),
              (Collection<? extends Map<?, ?>>) data);
          break;
        case BigExcel:
        case MapExcelGraph:
        case PDFTemplate:
        case TemplateExcel:
        case TemplateWord:
        default:
          throw new RuntimeException();
      }
      if (workbook != null) {
        if (excelExportParam.getFileName() != null) {
          String codedFileName = URLEncoder.encode(excelExportParam.getFileName(), "UTF8");
          headers.setContentDispositionFormData("attachment", codedFileName);
        }
        workbook.write(outputMessage.getBody());
      }
    }
    private Collection getActualData(Result r) {
      if (r != null && r.getData() != null) {
        Object data = r.getData();
        if (data instanceof PageInfo) {
          return ((PageInfo) data).getList();
        } else if (!(data instanceof Collection)) {
          data = Lists.newArrayList(data);
        } else {
          return (Collection) data;
        }
      }
      return Collections.emptyList();
    }
    @Override
    public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
      //不支持excel
      return false;
    }
    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
      return null;
    }
    @Override
    public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) {
      return super.canWrite(mediaType) && clazz == Result.class && support();
    }
    private boolean support() {
      ExcelExportParam param = getExcelExportParam();
      if (param == null || param.getExcelExport() == null || param.getExportParams() == null) {
        return false;
      }
      if (param.getExcelExport() == ExcelExport.NormalExcel) {
        return true;
      } else {
        logger.warn(param.getExcelExport() + " not supprot now!");
        return false;
      }
    }
    @Override
    public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
      super.write(o, contentType, outputMessage);
    }
  }

一时只是对准导出 由此在选取的时候如下

 @GetMapping
  @ApiOperation(value = "获取实体列表", notes = "")
  public Result list(S so) {
    PageHelper.startPage(so.getCurrentPage(), so.getPageSize());
    List<V> list = service.findAll();
    PageInfo pageInfo = new PageInfo(list);
    excelExportParam();
    return ResultGenerator.genSuccessResult(pageInfo);
  }
  protected void excelExportParam() {
    ExportParams ep = new ExportParams(null, "数据");
    ExcelExportParam<V> param = new ExcelExportParam<>();
    param.setClazz(voClazz);
    param.setExcelExport(ExcelExport.NormalExcel);
    param.setExportParams(ep);
    param.setFileName("文件.xls");
    F6Static.setExcelExportParam(param);
  }

当我们拜谒时如下

图片 2

 {
  "code": 200,
  "data": {
  "endRow": 10,
  "firstPage": 1,
  "hasNextPage": true,
  "hasPreviousPage": false,
  "isFirstPage": true,
  "isLastPage": false,
  "lastPage": 8,
  "list": [
  {
  "cellPhone": "13857445502",
  "idEmployee": 24201883434352650,
  "idOwnOrg": 23993199378825296,
  "idRole": 88,
  "idWxbStation": "332",
  "idWxbUser": "207",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 23993199378825296,
  "username": "lingweiqiche"
  },
  {
  "cellPhone": "",
  "idEmployee": 0,
  "idOwnOrg": 9999,
  "idRole": 4,
  "idWxbStation": "",
  "idWxbUser": "",
  "isAdmin": 0,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434356532,
  "username": "007"
  },
  {
  "cellPhone": "15715139000",
  "idEmployee": 24351585207523460,
  "idOwnOrg": 24201883434357600,
  "idRole": 89,
  "idWxbStation": "540",
  "idWxbUser": "298",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434357600,
  "username": "15715139000"
  },
  {
  "cellPhone": "",
  "idEmployee": 0,
  "idOwnOrg": 24201883434357600,
  "idRole": 216,
  "idWxbStation": "",
  "idWxbUser": "",
  "isAdmin": 0,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434357920,
  "username": "sunlingli"
  },
  {
  "cellPhone": "",
  "idEmployee": 24351585207425676,
  "idOwnOrg": 24201883434359384,
  "idRole": 90,
  "idWxbStation": "348",
  "idWxbUser": "227",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "opzUDs_v13WE500kxYMj6Xg_gFeE",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434359388,
  "username": "15952920979"
  },
  {
  "cellPhone": "",
  "idEmployee": 0,
  "idOwnOrg": 24201883434359790,
  "idRole": 91,
  "idWxbStation": "315",
  "idWxbUser": "175",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434359790,
  "username": "13809056211"
  },
  {
  "cellPhone": "18903885585",
  "idEmployee": 24201883434366164,
  "idOwnOrg": 24201883434359890,
  "idRole": 92,
  "idWxbStation": "317",
  "idWxbUser": "178",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434359892,
  "username": "18903885585"
  },
  {
  "cellPhone": "",
  "idEmployee": 24351585207425668,
  "idOwnOrg": 24201883434359924,
  "idRole": 93,
  "idWxbStation": "318",
  "idWxbUser": "179",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434359930,
  "username": "13372299595"
  },
  {
  "cellPhone": "",
  "idEmployee": 0,
  "idOwnOrg": 24201883434360052,
  "idRole": 94,
  "idWxbStation": "321",
  "idWxbUser": "188",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434360052,
  "username": "15221250005"
  },
  {
  "cellPhone": "",
  "idEmployee": 0,
  "idOwnOrg": 24201883434360070,
  "idRole": 95,
  "idWxbStation": "325",
  "idWxbUser": "198",
  "isAdmin": 1,
  "isDel": 0,
  "isGuideOpen": 0,
  "limitMac": 0,
  "openid": "",
  "password": "96e79218965eb72c92a549dd5a330112",
  "pkId": 24201883434360070,
  "username": "13837251167"
  }
  ],
  "navigateFirstPage": 1,
  "navigateLastPage": 8,
  "navigatePages": 8,
  "navigatepageNums": [
  1,
  2,
  3,
  4,
  5,
  6,
  7,
  8
  ],
  "nextPage": 2,
  "orderBy": "",
  "pageNum": 1,
  "pageSize": 10,
  "pages": 102,
  "prePage": 0,
  "size": 10,
  "startRow": 1,
  "total": 1012
  },
  "message": "SUCCESS"
  }

当访问 或者

日常来讲效果

图片 3

图片 4

鉴于这边的数量和查询有关 由此大家能够如此操作 易如反掌完毕了询问结果xls化!

图片 5

图片 6

总结

上述所述是作者给大家介绍的SpringBoot中的内容协商器图解,希望对大家全体助于,假诺大家有任何疑问请给自己留言,笔者会及时苏醒我们的。在此也特别谢谢大家对帮客之家网址的支撑!

背景 使用了restful的伴儿对于导出那一个须要本能正是拒绝的~破坏了restful的url的一致性【严谨矫...

本文由金冠53777-金冠娱乐53777-Welcome发布,转载请注明来源

关键词: