91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot中的內容協商器圖解

發布時間:2020-09-22 21:50:02 來源:腳本之家 閱讀:177 作者:波波維奇 欄目:編程語言

背景

使用了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頭里面也能看出

SpringBoot中的內容協商器圖解

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);
  }

當我們訪問時如下

http://127.0.0.1:8079/zeus/user

SpringBoot中的內容協商器圖解

 {
  "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"
  }

當訪問http://127.0.0.1:8079/zeus/user?format=xls 或者http://127.0.0.1:8079/zeus/user.xls

如下效果

SpringBoot中的內容協商器圖解

SpringBoot中的內容協商器圖解

由于這邊的數據和查詢有關 因此我們可以這樣操作http://127.0.0.1:8079/zeus/user.xls?pageSize=1000 輕而易舉實現了查詢結果xls化!

SpringBoot中的內容協商器圖解

SpringBoot中的內容協商器圖解

總結

以上所述是小編給大家介紹的SpringBoot中的內容協商器圖解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

昆明市| 焦作市| 吴江市| 新宾| 锡林浩特市| 英吉沙县| 益阳市| 通城县| 赤城县| 潼关县| 蓬安县| 郎溪县| 郁南县| 乌鲁木齐县| 南丹县| 四子王旗| 旬阳县| 东乌珠穆沁旗| 金沙县| 家居| 铁岭市| 河南省| 贵港市| 呈贡县| 斗六市| 徐水县| 搜索| 大兴区| 康马县| 丹江口市| 社旗县| 长兴县| 丹东市| 偏关县| 安国市| 黑水县| 青浦区| 梁河县| 舟山市| 雷波县| 曲沃县|