배경
RESTFUL 본능을 사용하여 이러한 요구를 내보내는 친구는 거부됩니다. ~ RESTFUL URL의 일관성을 파괴합니다 [엄격한 수정은 HTTP JSON 또는 RESTFUL입니다. 많은 친구들이 JSON을 노출시키고 직접 편안하게 부를 것입니다.]
위의 코드 생성기에서와 같이, 우리는 많은 코드를 생성 할 것입니다.
공개 초록 클래스 AbstractrestController <V 확장 VO, S 확장하여 PK는 Serializable> {Protected Class <V> voclazz; @autowired Private Service <v, s, pk> 서비스; public AbstractrestController () {typetoken <v> votype = new typetoken <v> (getClass ()) {}; voclazz = (class <v>) votype.getRawtype (); } @postmapping () @apioperation (value = "new Entity", notes = "") public result add (@requestbody v vo) {service.saveselective (vo); return resultgenerator.gensuccessresult (); } @deletemapping ( "/{id}") @apioperation (value = "delete entity", notes = "") public result delete (@pathvariable pk id) {service.deletebyid (id); return resultgenerator.gensuccessresult (); } @putMapping @apioperation (value = "update entity", notes = "") 공개 결과 업데이트 (@requestbody v vo) {service.up.updateByPrimaryKeySelective (VO); return resultgenerator.gensuccessresult (); } @getMapping @apioperation (value = "get enterity list", notes = "") 공개 결과 목록 (s so) {pagehelper.startPage (so.getCurrentPage (), so.getPagesize ()); 목록 <v> list = service.findall (); pageinfo pageinfo = new PageInfo (list); ExcelExportParam (); return resultgenerator.gensuccessresult (pageinfo); } 보호 된 void ExcelExportParam () {ExportParams ep = 새로운 ExportParams (null, "data"); ExcelExportparam <v> param = new ExcelExportParam <> (); param.setclazz (voclazz); param.setexcelexport (ExcelExport.normalexcel); param.setexportparams (ep); param.setfilename ( "file.xls"); f6static.setexcelexportparam (param); } @getMapping ( "/{id}") @apioperation (value = "get get get get get", notes = "") 공개 결과 세부 사항 (@pathvariable pk id) {v vo = service.findbyid (id); return resultgenerator.gensuccessresult (VO); } @deletemapping ( "/batch") @apioperation (value = "batch delete entity", notes = "") public result batchdelete (@requestparam String ids) {service.deleteByIds (ids); return resultgenerator.gensuccessresult (); } @getMapping ( "/batch") @apioperation (value = "batch get entity", notes = "") public result batchDetail (@requestParam String IDS) {list <v> vos = service.findbyIds (ids); return resultgenerator.gensuccessresult (vos); } @postmapping ( "/batch") @apioperation (value = "batch new Entity", 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만이 아닙니다.]
질문이 제기되면 로그인은 어떻습니까? 전통적인 솔루션은 로그인 로그 아웃입니다. 그렇다면 편안한 자원을 대체한다는 아이디어는 무엇입니까?
팁 : 로그인은 새 세션입니다. 로그 아웃은 삭제 세션입니다.
성취하다
위의 아이디어를 바탕으로, 우리는 자연스럽게 여러 결과를 동일한 URL로 반환하면 괜찮다고 생각 했습니까? [PDF, 하나의 버전, 하나의 버전, 하나의 버전, 하나의 버전, 하나의 버전]]]
빙고! 이것이 컨텐츠 협상가의 기원입니다
컨텐츠 협상자는 봄에 의해 만들어지지 않았으며, 실제로 HTTP 헤더에서 볼 수 있습니다.
1. 예를 들어, 영어 페이지로 영어 페이지로 돌아가는 것은 중국 페이지에 비해 너무 많습니다.
HTTP 프로토콜은 클라이언트가 각 기본 설정 범주에 대한 여러 옵션을 나열하고 각 선호도 옵션에 대한 우선 순위를 연관시킬 수있는 품질 값 (Q 값이라고 함)을 정의합니다.
허용 : 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. 그런 다음 수락 헤더와 같은 다른 매개 변수가 있습니다.
일반적으로 컨텐츠 협상가는 먼저 다음 솔루션을 가지고 있습니다
1. 헤더 수락 사용 :
이것은 일반적으로 교과서에 설명되어 있습니다. 이상적으로는이 방법이 최고이지만 브라우저 (즉, HTML 디스플레이)를 통해 리소스에 직접 액세스하려면 브라우저 차이로 인해 전송 된 헤더 헤더가 다릅니다. 이로 인해 서버가 귀하에게 어떤 형식의 데이터를 반환할지 알지 못할 것입니다. 다음은 브라우저의 승인 헤더입니다
Chrome : Application : Application/XML, Application/XHTML+XML, TextMl; Q = 0.9, 텍스트/일반; Q = 0.8, 이미지/png,*/*; q = 0.5 firefox : accept : text/html, application/xhtml+xml; q = 0.9,*/*; q = 0. 이미지/pjpeg, 응용 프로그램/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가 Taobao와 같은이 방법을 사용합니다.
그러나 다른 브라우저의 경우 허가서가 특히 통일되지 않을 수 있으므로 많은 구현이 2 3 솔루션을 선택합니다.
우리는 봄에 위의 두 솔루션을 채택합니다
먼저 컨텐츠 협상자를 구성하십시오
암호
@bean public viewresolver contentnegotiatiedviewresolver (contentnegotiationmanager manager) {// view resolvers viewresolver beannameviewresolver = new beannameviewresolver (); 목록 <viewresolver> resolvers = lists.newarraylist (beannameviewresolver); ContentNegotiatietViewResolver resolver = 새로운 ContentNegotiatingViewResolver (); Resolver.SetViewResolvers (Resolvers); Resolver.SetContentNegotiationManager (관리자); 리턴 리졸버; } @override public void configeRecontentNegotiation (contentNegotiationConfigurer configure) {configurer.favorPathextension (true) .usejaf (false) .favorParameter (true) .pavorametername ( "format") .ignoreaCcepTheader (true) .defaultContType (mediapolype. .mediatepe ( "json", mediaType.application_json) .mediatepe ( "xls", Excel_media_type); }해당 변환기를 만듭니다
private httpmessageconverter <botort> createexcelhttpmessageconverter () {excelhttpmessageconverter xcelhttpmessageconverter = new ExcelhttpmessageConverter (); excelhttpmessageconverter를 반환합니다. }Easy-POI를 사용하여 직접 데이터를 내보내십시오
/ * * Copyright (C) 2017. Lorem Ipsum Dolor Sit Amet, Consteretur adipiscing elit. * Morbi 비 Lorem Porttitor Neque Feugiat Blandit. ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum ordimentum fringilla. Maecenas Magna. * proin dapibus sapien vel ante. aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * 전정 코모도. UT Rhoncus Gravida Arcu. */ 패키지 com.f6car.base.web.converter; cn.fterturn.easypoi.excel.excelexportutil import; import com.f6car.base.common.result; import com.f6car.base.core.excelexport; import com.f6car.base.core.excelexportparam; com.github.pagehelper.pageinfo 가져 오기; import com.google.common.collect.lists; import org.apache.poi.ss.usermodel.workbook; 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.httpmessagenotwaritableException; import java.io.ioexception; import java.lang.reflect.type; import java.net.urlencoder; java.util.collection import; java.util.collections import; java.util.collections import; java.util.map import; static com.f6car.base.core.f6static.getexcelexportparam 가져 오기; / ** * @author qixiaobo */ public class ExcelhttpMessageConverter acbstracthttpmessageconverter angergendments gener genericttpmessageconverter <boodment> {public final mediape excel_media_type = new MediaType ( "Application", "vnd.ms"); public ExcelhttpmessageConverter () {super (excel_media_type); } @override protected boolean suppors (class <?> clazz) {return false; } @Override Protected Object ReadInternal (class <?> clazz, httpinputMessage inputMessage) IoException, httpmessagenoTreadableException {return null; } @override protected void writeNternal (Object O, httpoutPutMessage outputMessage)은 ioException, httpmessagenotWablexception {httpheaders headers = outputmessage.getheaders (); 수집 데이터 = getActualData ((결과) o); ExcelExportParam ExcelExportParam = getExcelexportParam (); 통합 문서 통합 문서; switch (excelexportparam.getexcelexport ()) {case normalexcel : workbook = ExcelExportUtil.exportexcel (ExcelExportParam.getexportparams (), (class <?>) ExcelExportParam.getClazz (collection <?>); 부서지다; CASE MAPEXCEL : workbook = ExcelExportUtil.exportexcel (ExcelExportParam.getexportParams (), ExcelExportParam.getexcelexportentities (), (collection <? extends map <?,? >>) 데이터); 부서지다; CASE BIGEXCEL : CASE MAPEXCELGRAPH : CASE PDFTEMPLATE : CASE TEMPLESTEXCEL : CASE TEMPLATEWORD : 기본값 : 새 RUNTIMEEXCEPTION (); } if (workbook! = null) {if (excelExportParam.getFilename ()! = null) {String CodedFilename = urlencoder.encode (ExcelExportParam.getFilename (), "utf8"); headers.setContentDispositionFormData ( "첨부 파일", codedFilename); } workbook.write (outputMessage.getBody ()); }} private collection getActualData (result r) {if (r! = null && r.getData ()! = null) {Object Data = r.getData (); if (pageinfo) {return ((pageinfo) data) .getList (); } else if (! (! } else {return (수집) 데이터; }} return collections.emptyList (); } @override public boolean canread (유형 유형, class <?> contextclass, mediaType mediaType) {// excel return false가 지원되지 않습니다. } @override public Object 읽기 (유형 유형, 클래스 <?> 컨텍스트 클래스, httpinputMessage inputMessage)는 ioexception, httpmessagenoTreadableException {return null; } @override public boolean canwrite (유형 유형, 클래스 <?> 클라그, 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 () + "지금 지원하지 않음!"); 거짓을 반환합니다. }} @override public void write (Object O, 유형 유형, mediaType contentType, httpoutPutmessage outputMessage)는 ioexception, httpmessagenotwablexception {super.write (o, contenttype, outputmessage)를 던졌습니다. }}당분간 수출을위한 것이므로 다음과 같이 사용될 때
@getMapping @apioperation (value = "get enterty list", notes = "") 공개 결과 목록 (s so) {pagehelper.startPage (so.getCurrentPage (), so.getPagesize ()); 목록 <v> list = service.findall (); pageinfo pageinfo = new PageInfo (list); ExcelExportParam (); return resultgenerator.gensuccessresult (pageinfo); } 보호 된 void ExcelExportParam () {ExportParams ep = 새로운 ExportParams (null, "data"); ExcelExportparam <v> param = new ExcelExportParam <> (); param.setclazz (voclazz); param.setexcelexport (ExcelExport.normalexcel); param.setexportparams (ep); param.setfilename ( "file.xls"); f6static.setexcelexportparam (param); }우리가 방문 할 때
http://127.0.0.1:8079/zeus/user
{ "code": "data": { "endrow": 10, "firstpage": 1, "hasnextpage": true, "haspreviouspage": false, "isfirstpage": true, "islastpage": "lastpage": 8, "list": [{13857445552 ","idemmoree ": 242018883434352650, "idownorg": 23993199378825296, "idrole": 88, "idwxbstation": "332", "idwxbuser": "207", "Isadmin": 1, "Isdel": 0, "isguideopen": 0, "": ":": ":": ": 0,": 0, ": 0,": 0, ": 0,"isguideopen " "", "비밀번호": "96E79218965EB72C92A549DD5A330112", "PKID": 2399319937825296, "사용자 이름": "Lingweiqiche"}, "핸드폰": "" ","idcloyee ": 0,"idcloyee " 4, "idwxbStation": "", "", "idwxbuser": "", "Isadmin": 0, "Isdel": 0, "isguideopen": 0, "Limitmac": 0, "OpenID": ","Password ":"POASSS " 24201883434356532, "사용자 이름": "007"}, { "핸드폰": "15715139000", "idemployee": 24351585207523460, "idownorg": 24201883434357600, "idrole": 89, "idwxbstation": ": "idwxbuser": "298", "Isadmin": 1, "Isdel": 0, "IsguideoPen": 0, "LimitMac": 0, "OpenID": "", "Password": "96E79218965EB72C92A549DD5A330112" "사용자 이름": "15715139000"}, { "핸드폰": "" ","idemployee ": 0,"idownorg ": 242018883434357600,"idrole ": 216,"idwxbstation ":" ","idwxbuser ":" ","isadmin ": 0,": ":" "" "" "" "" "" 0, "limitmac": 0, "openid": "", "password": "96E79218965EB72C92A549DD5A330112", "PKID": 24201883434357920, "사용자 이름": "SUNLINGLI"}, { "" "", "", "", "": ":" 24351585207425676, "idownorg": 242018883434359384, "idrole": 90, "idwxbstation": "348", "idwxbuser": "227", "Isadmin": 1, "Isdel": 0, ": 0," ":": ":": ":": ": 0,": 0, ": 0,": 0, "Isguideopen" "opzuds_v13we500kxymj6xg_gfee", "password": "96e79218965eb72c92a549dd5a330112", "pkid": 24201883434359388, "username": "1595292099", { "": "" ": "Idemployee": 0, "Idownorg": 24201883434359790, "idrole": 91, "idwxbstation": "315", "idwxbuser": "175", "Isadmin": 1, "Isdel": 0, "isguideopen": 0, "" "" "" "" "" "" "" "" "" "96E79218965EB72C92A549DD5A330112", "PKID": 2420183434359790, "사용자 이름": "13809056211"}, { "핸드폰": "18903885585" "idownorg": 242018883434359890, "idrole": 92, "idwxbStation": "317", "idwxbuser": "178", "Isadmin": "Isdel": 0, "isguideopen": 0, "limitmac": 0, "password", "" "" "96E79218965EB72C92A549DD5A330112", "PKID": 2420183434359892, "사용자 이름": "18903885585"}, { "휴대폰": "" ","Idemployee ":"idemployee ": 24201883434359924, "idrole": 93, "idwxbstation": "318", "idwxbuser": "179", "Isadmin": "Isdel": 0, "Isguideopen": 0, "Limitmac": 0, "Openid": "": "": "": ":": ":": ":": ":": ":": ":": 0, "Isguideopen": "Isguideopen": "Isguideopen": 0, "Isguideopen": 0, "96E79218965EB72C92A549DD5A330112", "PKID": 2420183434359930, "username": "13372299595"}, { "핸드폰": "", "idemployee": 0, "Idownorg": 24201834362. "Idrole": "94,"idwxbStation ":"321 ","idwxbuser ":"188 ","Isadmin ": 1,"Isdel ": 0,"isguideopen ": 0,"limitmac ": 0,"openid ":" ","password ":"96e79218965eb72a59dd5a " "pkid": 242018883434360052, "사용자 이름": "15221250005"}, { "핸드폰": "", "idemployee": 0, "idownorg": 2420188343434360070, "idrole": 95, "idwxbstation", "idwxbuser", ":"idwxbstation " "ISADMIN": "ISDEL": 0, "ISGUIDEOPEN": 0, "LIMITMAC": 0, "OpenID": "", "Password": "96E79218965EB72C92A549DD5A330112", "PKID": 2420183434360070, "138377": "1383434360070" }], "navigatefirstpage": 1, "navigatelastpage": 8, "navigatePages": 8, "navigatePagenums": [nevigatePagenums ": [nextPage": 2, "Orderby": "" ","pagenum ": 1,"Pages ": 10,"102, ":": "" "" "" " "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에 액세스 할 때
다음 효과
여기의 데이터는 쿼리와 관련이 있으므로 http://127.0.0.1:8079/zeus/user.xls?pagesize=1000 xlsize xlsization의 xlsization을 쉽게 알 수 있습니다!
요약
위의 것은 SpringBoot에서 편집자가 소개 한 컨텐츠 협상자의 그림입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!