根据接口文档书写接口,并在前端调用接口返回显示出数据(加下载)
发布日期:2021-10-24 03:50:06 浏览次数:1 分类:技术文章

本文共 20777 字,大约阅读时间需要 69 分钟。

---恢复内容开始---

 1.首先来看接口文档(其中一个接口):

接口的编写:

1 /** 2      * 7.11 余额明细查询接口 3      *  4      * @param token 5      * @param pageNum 6      *            非必填 分页查询当前页数,默认为 1 7      * @param pageSize 8      *            非必填 每页记录数,默认为 20 9      * @param orderId10      *            非必填 订单号11      * @param startDate12      *            非必填 开始日期,格式必须:yyyyMMdd13      * @param endDate14      *            非必填 截止日期,格式必须:yyyyMMdd15      * @return16      */17     public String getBalanceDetail(String token, int pageNum, int pageSize, String orderId, String startDate, String endDate);

 server中对于接口实现的编写:

1 private static final String API_URL_BASE = GlobalCache.getSystemCache("jdNewApiUrlBase");2     // 通用返回3     private static final String SUCCESS = "success";4     private static final String RESULT_MESSAGE = "resultMessage";5     private static final String RESULT_CODE = "resultCode";6     private static final String RESULT = "result";
1 /** 2      * 7.11 余额明细查询接口 3      *  4      * @param token 5      * @param pageNum 6      *            非必填 分页查询当前页数,默认为 1 7      * @param pageSize 8      *            非必填 每页记录数,默认为 20 9      * @param orderId10      *            非必填 订单号11      * @param startDate12      *            非必填 开始日期,格式必须:yyyyMMdd13      * @param endDate14      *            非必填 截止日期,格式必须:yyyyMMdd15      * @return16      */17     @Override18     public String getBalanceDetail(String token, int pageNum, int pageSize, String orderId, String startDate, String endDate) {19         Map
paramMap = new HashMap<>();20 paramMap.put("token", token);21 if (pageNum > 0) {22 paramMap.put("pageNum", pageNum);23 }24 if (pageSize > 0) {25 paramMap.put("pageSize", pageSize);26 }27 if (StringUtils.isNotBlank(orderId)) {28 paramMap.put("orderId", orderId);29 }30 if (StringUtils.isNotBlank(startDate)) {31 paramMap.put("startDate", startDate);32 }33 if (StringUtils.isNotBlank(endDate)) {34 paramMap.put("endDate", endDate);35 }36 String responseStr;37 try {38 responseStr = HttpsUtil.post(API_URL_BASE + "/price/getBalanceDetail", paramMap);39 } catch (Exception e) {40 LogUtil.ERROR.error("调用接口失败:" + e);41 throw new AppException("调用接口失败");42 }43 Map
detailMsgMap = toHashMap(responseStr);44 if (isQuerySuccess(detailMsgMap)) {45 return detailMsgMap.get(RESULT).toString();46 } else {47 LogUtil.ERROR.error("调用接口返回失败:" + responseStr);48 throw new AppException("系统出现异常,错误代码[" + detailMsgMap.get(RESULT_CODE) + "],错误信息[" + detailMsgMap.get(RESULT_MESSAGE) + "]");49 }50 }

 在controller里面对接口进行调用:

/**     * 查询JD预存余额     * @param request     * @param response     * @return     * @throws IOException     */    @RequestMapping(params = "method=deposit4JD")    public ModelAndView deposit4JD(HttpServletRequest request,HttpServletResponse response,                    String startDate,String endDate,String orderId) {        try {            //获取token            String token = jdServer.getToken();            String map = jdServer.getBalance(token, 4);            map = map.substring(0, map.length()-2);                        //首次加载页面不查询列表数据            if ("GET".equalsIgnoreCase(request.getMethod()))            {                return new ModelAndView("/pages/balancesheet/JDdeposit");            }            Map mapDetail = new HashMap<>();                        Pager pager = RequestManager.getPager(request);            int pageSize = pager.getPageSize();            int currentPage = (int) pager.getPageNumber();            //token验证、当前页面、每页显示、订单号、开始时间、结束时间            mapDetail = JSONObject.fromObject(jdServer.getBalanceDetail(token, currentPage, pageSize, orderId,startDate, endDate));                        /*if(paginater==null){                setAttribute(request, "count", Long.toString(0));                setAttribute(request, "beans", null);            }else{                setAttribute(request, "beans", paginater.getData());            }    */            int total = (int) mapDetail.get("total");            if(total > 0){                request.setAttribute("isData", "1");            }            setAttribute(request, "count", mapDetail.get("total").toString());                        request.setAttribute("map", map);            Object objData = mapDetail.get("data");            request.setAttribute("objData", objData);            request.setAttribute("startDate", startDate);            request.setAttribute("endDate", endDate);            request.setAttribute("orderId", orderId);        } catch (BizException e) {            e.printStackTrace();            String str = "调用JD查询接口查询预存额明细发生错误!";            LogUtil.ERROR.error(str + ":" + e.getMessage());            ErrorLog error = ErrorLogUtil.getErrorLog(e, request, this.getClass().getName(), str);            elServer.save(error);            throw new BizException(str);        }        return new ModelAndView("/pages/balancesheet/JDdeposit");            }

值可以让页面获取到:

1 ----------------------------  2   3     
4
5

京东预存款剩余余额:${map }元

6
7
10
11
12
13
14
查询条件 15
16
17
18
19
20
22
23
24
25
26
27
28
29
31
32
33
34
35
36
37
38
39
40
41
42 43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
JD预存额明细 60
61
68
69
70
71
72
73
74
75
76 77
78
96
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 95
97
98 <%--
--%> 99
100 <%--
--%>101
102
103
104 <%--
--%>105
106
107
117
118 119 120
121
序号 创建时间 交易金额 账户名称 订单号 交易类型 交易流水号 备注
${status.index+1} ${par['id']} ${par['createdDate']}
普通商户[${par['accountType']}]
${par['amount']} ${par['pin']} ${par['orderId']} ${par['tradeType']} ${par['tradeTypeName']} ${par['tradeNo']} 108
109
110 ${fn:substring(par['notePub'],0,30)}...111
112
113 ${par['notePub']}114
115
116
122
123 124 125
126
127 128
129
130
131
132 133
134 <%@ include file="../../pages_public/include/public_foot.jsp" %>135
136 137 151

上面还有一个Excel文档的下载方式,调用controller里面的下载方法:

1 @RequestMapping(params = "method=exportExcel") 2     public ModelAndView exportExcel(HttpServletRequest request, HttpServletResponse response,  3             String startDate,String endDate,String orderId) 4             throws IOException { 5         try { 6             ExportExcle exportExcle = new ExportExcle();  //新建导出对象 7             Object[] headerArray = new Object[] {  //表头数组 8                     "创建时间", 9                     "交易金额",10                     "账户名称",11                     "订单号",12                     "交易类型","交易流水号","备注"};13             exportExcle.setTitleAndHeader("JD预存额明细", headerArray);  //设置标题和表头----------step_114 15             // 数据对应的数组List16             for(Pager pager : exportExcle.getPagerList()) {17                 List
contentList = new ArrayList<>(); //内容列表18 // ---------- 将从数据库获取的数据封装成List开始19 Map mapDetail = new HashMap<>();20 String token = jdServer.getToken();21 //Pager pager = RequestManager.getPager(request);22 int pageSize = 1000;//pager.getPageSize();23 int currentPage = 1;//(int) pager.getPageNumber();24 //token验证、当前页面、每页显示、订单号、开始时间、结束时间25 mapDetail = JSONObject.fromObject(jdServer.getBalanceDetail(token, currentPage, pageSize, orderId,startDate, endDate));26 JSONArray objData = (JSONArray)mapDetail.get("data");27 for(Object object : objData) {28 Map map = (Map) object;29 Object[] objArr = new Object[] {30 map.get("createdDate"),31 map.get("amount"),32 map.get("pin"),33 map.get("orderId"),34 map.get("tradeTypeName"),35 map.get("tradeNo"),36 String.valueOf(map.get("notePub")).trim()37 };38 contentList.add(objArr); //增加内容39 }40 // ---------- 将从数据库获取的数据封装成List结束41 exportExcle.setContentPagerDate(contentList, pager); //设置需要导出的内容列表----------step_242 }43 exportExcle.exportWorkbook(response); //将文件写入输出流----------step_344 } catch (Exception e) {45 LogUtil.MSG.error("下载失败了", e);46 }47 return null;48 49 }

在下载Excel时,调用了封装好的exportExcel里面的方法,其封装类如下:

1 package com.eptok.util;  2   3 import java.io.ByteArrayOutputStream;  4 import java.io.FileOutputStream;  5 import java.io.IOException;  6 import java.io.OutputStream;  7 import java.io.UnsupportedEncodingException;  8 import java.math.BigDecimal;  9 import java.text.DecimalFormat; 10 import java.util.ArrayList; 11 import java.util.HashMap; 12 import java.util.List; 13 import java.util.Map; 14  15 import javax.servlet.http.HttpServletResponse; 16  17 import org.apache.poi.hssf.util.HSSFColor; 18 import org.apache.poi.ss.usermodel.Cell; 19 import org.apache.poi.ss.usermodel.CellStyle; 20 import org.apache.poi.ss.usermodel.Font; 21 import org.apache.poi.ss.usermodel.HorizontalAlignment; 22 import org.apache.poi.ss.usermodel.Row; 23 import org.apache.poi.ss.usermodel.Sheet; 24 import org.apache.poi.ss.usermodel.VerticalAlignment; 25 import org.apache.poi.ss.util.CellRangeAddress; 26 import org.apache.poi.xssf.streaming.SXSSFSheet; 27 import org.apache.poi.xssf.streaming.SXSSFWorkbook; 28  29 import hikefa.core.web.page.Pager; 30  31 public class ExportExcle { 32  33     /** 最大导出行数*/ 34     public static final int MAX_ROWS = 500000; 35      36     /** 分页行数*/ 37     public static final int PAGING_ROWS = 50000; 38      39     /** SXSSF操作行数*/ 40     public static final int SXSSF_ROWS = 100; 41  42     /** 缓存行数*/ 43     public static final int CACHE_ROWS = 1000; 44  45     /** 创建Workbook*/ 46     SXSSFWorkbook workbook = new SXSSFWorkbook(SXSSF_ROWS); 47  48     /** 当前Sheet*/ 49     Sheet sheet; 50  51     /** 内容总数*/ 52     private int contentCount = 0; 53      54     /** 总页数*/ 55     private int pageCount; 56  57     /** 分页列表*/ 58     private List
pagerList = new ArrayList<>(); 59 60 /** 标题*/ 61 private String title; 62 63 /** 表头数组*/ 64 private Object[][] headerArray; 65 66 /** 导出列数*/ 67 private int colCount; 68 /** 标题行数*/ 69 private int titleRows = 0; 70 /** 标题行数*/ 71 private int headerRows = 0; 72 73 /** 样式Map*/ 74 private Map
styleMap = new HashMap<>(); 75 76 /** 列宽数组*/ 77 private Integer[] intArray; 78 79 /** 构造方法*/ 80 public ExportExcle() { 81 } 82 // //***Demo*** 83 // ExportExcle exportExcle = new ExportExcle(); //新建导出对象 84 // int contentCount = 0; //从数据库获取内容总数(可选)----------step_0(数据量大于50000,建议设置) 85 // exportExcle.setContentCount(contentCount); //设置内容总数(可选)----------step_0(数据量大于50000,建议设置) 86 // Object[] headerArray = new Object[] { //表头数组 87 // "", 88 // ""}; 89 // exportExcle.setTitleAndHeader("标题", headerArray); //设置标题和表头----------step_1 90 // //遍历分页列表进行操作 91 // for(Pager pager : exportExcle.getPagerList()) { 92 // List
contentList = new ArrayList<>(); //内容列表 93 // // ---------- 将从数据库获取的数据封装成List开始 94 // Paginater paginater = server.findSplitPage(pager); 95 // for(Object object : paginater.getData()) { 96 // Map
map = (Map
) object; 97 // Object[] objArr = new Object[] {}; 98 // contentList.add(objArr); //增加内容 99 // }100 // // ---------- 将从数据库获取的数据封装成List结束101 // exportExcle.setContentPagerDate(contentList, pager); //设置需要导出的内容列表----------step_2102 // }103 // exportExcle.exportWorkbook(response); //将文件写入输出流----------step_3104 105 106 /** step_0:设置内容总数(不设置则默认为单页导出)*/107 public void setContentCount(int contentCount) {108 this.contentCount = contentCount; //设置内容总数109 }110 111 /** step_1:设置标题和表头数组(单行),并初始化参数*/112 public void setTitleAndHeader(String title, Object[] headerArray) {113 Object[][] headerArrayTemp = new Object[1][];114 headerArrayTemp[0] = headerArray;115 setTitleAndHeader(title, headerArrayTemp);116 }117 /** step_1:设置标题和表头数组(多行),并初始化参数*/118 public void setTitleAndHeader(String title, Object[][] headerArray) {119 this.title = title;120 this.headerArray = headerArray;121 parameterChecking(); //校验参数122 }123 124 /** step_2:设置需要导出的内容列表*/125 public void setContentPagerDate(List
contentList, Pager pager) {126 LogUtil.APP.info("开始将[" + title + "] - 第" + pager.getPageNumber() +"页数据写入Excle文件 - " 127 + DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));128 if(null == contentList || contentList.isEmpty()) {129 throw new IllegalArgumentException("查询不到需要导出的数据[contentList]");130 }131 // ---------- 导出数据到Excle文件Sheet页开始132 String sheetName = "第" + pager.getPageNumber() +"页 - 共" + pageCount + "页"; //sheet名称133 sheet = workbook.createSheet(sheetName); //创建工作表134 writeTitle(); //写入标题135 writeHeader(); //写入表头数组136 writeContent(contentList); //写入内容列表137 autoColumnSize(); //自适应列宽,并冻结窗格138 // ---------- 导出数据到Excle文件Sheet页结束139 contentList.clear(); //清空列表140 LogUtil.APP.info("将[" + title + "] - 第" + pager.getPageNumber() +"页数据写入Excle文件结束 - " 141 + DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));142 }143 144 /** step_3:将文件写入输出流*/145 public void exportWorkbook() {146 exportWorkbook("D:/"); //默认导出到D盘根目录147 }148 /** step_3:将文件写入输出流*/149 public void exportWorkbook(String path) {150 FileOutputStream fos = null;151 try {152 fos = new FileOutputStream(path + title + ".xlsx");153 workbook.write(fos);154 ((SXSSFWorkbook) workbook).dispose();155 } catch (IOException e) {156 e.printStackTrace();157 } finally {158 if (fos != null) {159 try {160 fos.close();161 } catch (IOException e) {162 e.printStackTrace();163 }164 }165 }166 }167 /** step_3:将文件写入输出流*/168 public void exportWorkbook(HttpServletResponse response) {169 ByteArrayOutputStream baos = null;170 OutputStream os = null;171 try {172 baos = new ByteArrayOutputStream();173 workbook.write(baos);174 ((SXSSFWorkbook) workbook).dispose();175 String fileName = new String(title.getBytes("gbk"), "ISO8859-1");176 response.reset(); // 清空输出流177 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");178 response.setContentType("application/msexcel");179 response.setContentLength(baos.size());180 os = response.getOutputStream();181 baos.writeTo(os);182 os.flush();183 } catch (IOException e) {184 e.printStackTrace();185 } finally {186 if (baos != null) {187 try {188 baos.close();189 } catch (IOException e) {190 e.printStackTrace();191 }192 }193 if (os != null) {194 try {195 os.close();196 } catch (IOException e) {197 e.printStackTrace();198 }199 }200 }201 }202 203 204 // --------------------------------------------------调用的方法--------------------------------------------------205 206 207 /** 校验参数*/208 private void parameterChecking() {209 if(null == title) {210 throw new IllegalArgumentException("标题未设置");211 }212 if(null == headerArray || headerArray.length == 0) {213 throw new IllegalArgumentException("表头数组未设置");214 } else {215 if(null != headerArray[0] && 0 < headerArray[0].length) {216 headerRows = headerArray.length; //设置表头行数217 colCount = headerArray[0].length; //设置导出列数218 intArray = new Integer[colCount]; //初始化列宽数组219 } else {220 throw new IllegalArgumentException("无法确定导出列数");221 }222 }223 if(contentCount <= 0) {224 contentCount = PAGING_ROWS; //默认为单页导出225 }226 setPagerList(); //设置分页信息227 initStyleMap(); //初始化样式Map228 }229 230 /** 设置分页列表*/231 private void setPagerList() {232 if(contentCount > MAX_ROWS) {233 contentCount = MAX_ROWS;234 }235 //计算总页数236 pageCount = contentCount % PAGING_ROWS > 0 ? contentCount / PAGING_ROWS + 1 : contentCount / PAGING_ROWS;237 //设置分页列表238 for (int i = 1; i <= pageCount; i++) {239 // int paging = i == pageCount && contentCount % PAGING_ROWS > 0 ? 240 // contentCount % PAGING_ROWS : PAGING_ROWS; //当前分页行数241 // pagingList.add(i, new Pager(i, paging));242 pagerList.add(new Pager(i, PAGING_ROWS));243 }244 }245 /** 获取分页列表*/246 public List
getPagerList() {247 return pagerList;248 }249 250 251 // --------------------------------------------------Excle操作--------------------------------------------------252 253 254 /** 写入表头标题*/255 private void writeTitle() {256 //创建行对象257 Row row = sheet.createRow(0); //创建行对象258 Cell cell = row.createCell(0); //创建单元格259 cell.setCellValue(title); //写入内容260 setRowStyle(0, styleMap.get("titleStyle")); //设置行样式261 mergedRegion(0, 0, 0, colCount-1); //合并单元格262 titleRows = 1; //记录标题行数263 }264 265 /** 写入表头数组headerArray[row][col]*/266 private void writeHeader() {267 for(int rowNum=0; rowNum < headerRows; rowNum++) {268 if(null == headerArray[rowNum] || 0 == headerArray[rowNum].length) {269 continue; //行数据为空,跳出当次循环270 }271 //创建行对象272 Row row = sheet.createRow(rowNum + titleRows);273 for(int colNum=0; colNum < colCount; colNum++) {274 Cell cell = row.createCell(colNum); //创建单元格275 cell.setCellStyle(styleMap.get("headerStyle")); //设置表头样式276 if(null == headerArray[rowNum][colNum] || "*".equals(headerArray[rowNum][colNum])) {277 continue; //单元格数据为空,跳出当次循环278 }279 setCellValue(cell, headerArray[rowNum][colNum], colNum); //写入内容值280 }281 }282 }283 284 /** 写入内容列表contentList*/285 private void writeContent(List
contentList) {286 for(int rowNum = 0; rowNum < contentList.size(); rowNum++) {287 Object[] array = contentList.get(rowNum);288 if(null == array || 0 == array.length) {289 continue; //数组为空,跳出当次循环290 }291 //创建行对象292 Row row = sheet.createRow(rowNum + titleRows + titleRows); //在表头之后293 for(int colNum = 0; colNum < array.length; colNum++) {294 if(null == array[colNum]) {295 continue; //跳出当次循环296 }297 Cell cell = row.createCell(colNum); //创建单元格298 cell.setCellStyle(styleMap.get("contentStyle")); //设置样式299 setCellValue(cell, array[colNum], colNum); //写入内容值300 }301 //每当行数达到设置的值就刷新数据到硬盘,以清理内存302 if(rowNum % CACHE_ROWS == 0){303 try {304 ((SXSSFSheet) sheet).flushRows();305 } catch (IOException e) {306 e.printStackTrace();307 }308 }309 }310 autoMergedRegion(); //自动合并单元格311 }312 313 /** 自适应列宽*/314 private void autoColumnSize() {315 /*//自适应列宽316 for(int colNum=0; colNum

完!!!!

转载于:https://www.cnblogs.com/1987721594zy/p/10032073.html

转载地址:https://blog.csdn.net/weixin_30687587/article/details/96944250 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:终于把Apollo存储加密这件事搞定了
下一篇:从串口频繁读取数据,关闭时卡死

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年03月30日 04时49分07秒