2019年5月29日,新公司,新项目。转眼一个月了,经过这段时间的适应感觉自己还能挺住。今天趁着周末,也趁着工作需求暂时能够告一段落,总结总结这段时间遇到的坑。
坑1:前后端分离,进行适配(老系统重构升级,页面已经调试完成)
需求描述:以前没怎么搞过前后端分离的项目,新公司新项目使用的恰恰就是前后端分离。于是虚心请教,自主学习,开始准备将公司大佬搞到一半的适配接手,还好有个模板已经适配完了,可以照猫画虎。对了前端用的Vue.JS
需求实现:以下标红的代码即跟后端代码关联起来的地方(target后面的地址一定要能够访问)
module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'http://localhost:8080/', changeOrigin: true, pathRewrite: { '^/api': '' } } }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- devtool: 'cheap-module-eval-source-map', cacheBusting: true, cssSourceMap: true },
坑2:第一步完成之后,第二步就很简单了,页面访问哪个方法,在后台就找到哪个方法就行,前后端一致即可,跟正常没有前后端分离一样,不过因为我现在用的vuejs所以返回格式需要修改。
坑3:介绍一下vuejs以及el组件的使用
select选择器的使用:
<el-select @change="changeBank()" v-model="bankIdList" multiple size="small" collapse-tags style="margin-left: 20px;" placeholder="请选择分行(可多选)"> <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"> </el-option> </el-select>
需要在vue的date中添加options属性
<script> export default { name: "Work-Push", data(){ return { closeBtn:false, table:[], wo_id:'', options: [], bankIdList: [], } },
并开始赋值,
methods:{ queryList(){ this.utils.post(this,'getWorkOrderReqRow.do',{orderId:this.wo_id},d=>{ this.table = d; }); }, // 加载所有分行 loadAllBranch() { console.log(1); this.utils.post(this,'allBranchForVue.do',{},d=>{ console.log(d); this.options = d; }); }, },
切记一定要在初始化时,将方法加载执行,因为选择在跳转到这个页面就要进行加载选择项,所以放在初始化中
created(){ this.wo_id = this.$route.params.id; console.log(this.wo_id); this.queryList(); //查询方法 this.loadAllBranch(); }
在vuejs中有date、methods、watch、created,分别代表数据、方法、监听、初始化,如下代码所示
<script> export default { name: "Work-Push", data(){ return { closeBtn:false, table:[], wo_id:'', options: [], bankIdList: [], } }, methods:{ queryList(){ this.utils.post(this,'getWorkOrderReqRow.do',{orderId:this.wo_id},d=>{ this.table = d; }); }, // 加载所有分行 loadAllBranch() { console.log(1); this.utils.post(this,'allBranchForVue.do',{},d=>{ console.log(d); this.options = d; }); }, changeBank() { console.log(2); console.log(this.bankIdList); }, pushWorkOrder(){ this.utils.post(this,'addWorkOrder.do',{orderId:this.wo_id,bankIdList:JSON.stringify(this.bankIdList)},d=>{ this.closeBtn = true; if(d == 'success'){ this.$message({ message: '推送成功', type: 'success' }); }else if(d == 'finish'){ this.$message({ message: '已推送成功,请勿重复推送', type: 'success' }); }else{ this.$message({ message: '推送失败' }); } }); }, off(){ this.utils.post(this,'updateWorkOrderStatu.do',{orderId:this.wo_id},d=>{ this.closeBtn = true; if(d == 'success'){ this.$message({ message: '关闭成功', type: 'success' }); } }); this.changePath('/work-order'); } }, watch: { $route: { deep: true, handler() { this.wo_id = this.$route.params.id; } } }, created(){ this.wo_id = this.$route.params.id; console.log(this.wo_id); this.queryList(); this.loadAllBranch(); } } </script>
关于Element组件,直接去:https://element.eleme.cn/#/zh-CN/component/installation 这个网站学习即可,随用随查。
比如用到button按钮组件。搜索之后就会出现如下图
点击显示代码,就会出现以下所有按钮类型对应的代码,直接复制粘贴即可使用。
<el-row> <el-button>默认按钮</el-button> <el-button type="primary">主要按钮</el-button> <el-button type="success">成功按钮</el-button> <el-button type="info">信息按钮</el-button> <el-button type="warning">警告按钮</el-button> <el-button type="danger">危险按钮</el-button> </el-row> <el-row> <el-button plain>朴素按钮</el-button> <el-button type="primary" plain>主要按钮</el-button> <el-button type="success" plain>成功按钮</el-button> <el-button type="info" plain>信息按钮</el-button> <el-button type="warning" plain>警告按钮</el-button> <el-button type="danger" plain>危险按钮</el-button> </el-row> <el-row> <el-button round>圆角按钮</el-button> <el-button type="primary" round>主要按钮</el-button> <el-button type="success" round>成功按钮</el-button> <el-button type="info" round>信息按钮</el-button> <el-button type="warning" round>警告按钮</el-button> <el-button type="danger" round>危险按钮</el-button> </el-row> <el-row> <el-button icon="el-icon-search" circle></el-button> <el-button type="primary" icon="el-icon-edit" circle></el-button> <el-button type="success" icon="el-icon-check" circle></el-button> <el-button type="info" icon="el-icon-message" circle></el-button> <el-button type="warning" icon="el-icon-star-off" circle></el-button> <el-button type="danger" icon="el-icon-delete" circle></el-button> </el-row>
http接口的认识:不同系统之间传输信息。
需求描述:A系统向B系统推送工单,因为数据较为简单,而且都是我们公司自己的系统,所以直接使用Http接口进行传递。
需求实现:
/** * 模拟请求 * * @param url 资源地址 * @param map 参数列表 * @param encoding 编码 * @return * @throws ParseException * @throws IOException */ public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{ String body = ""; //创建httpclient对象 CloseableHttpClient client = HttpClients.createDefault(); //创建post方式请求对象 HttpPost httpPost = new HttpPost(url); //装填参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(map!=null){ for (Map.Entry<String, String> entry : map.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //设置参数到请求对象中 httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); System.out.println("请求地址:"+url); System.out.println("请求参数:"+nvps.toString()); //设置header信息 //指定报文头【Content-type】、【User-Agent】 httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = client.execute(httpPost); //获取结果实体 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, encoding); } EntityUtils.consume(entity); //释放链接 response.close(); return body; }
/** * 将工单推送给分行 * @throws IOException * */ @RequestMapping("pushWorkOrder") public void pushWorkOrder(HttpServletResponse response, HttpServletRequest request) throws IOException{ //String orderId = "&orderID="+ HttpRequestUtil.urlEncode(request.getParameter("orderID"),"utf-8"); String orderId = request.getParameter("orderID"); WorkOrder workOrder=workOrderService.getWorkOrderByID(orderId); if(workOrder==null) { ResultUtil.Error(response, "没有对应的工单号"); } List<RequestRow> requestRowList = requestRowService.listRequestRowByWoId(orderId); String rowList = com.alibaba.fastjson.JSON.toJSON(requestRowList).toString(); String wo = com.alibaba.fastjson.JSON.toJSON(workOrder).toString(); Map<String,String> params = new HashMap<>(); params.put("requestRows",rowList); params.put("workOrder",wo); String detUrl = "http://127.0.0.1:8080/firewall/getWorkOrder.do"; String result = HttpRequestUtil.send(detUrl,params,"utf-8"); String msg = result.equals("success") ? "success" : "error"; try { response.getWriter().write(msg); } catch (IOException e) { e.printStackTrace(); } }
接下来就是B系统接收到信息之后,对数据处理以及返回信息。
/** * 获取8088的推送信息 * @param response * @param request * @param session * @return * @throws ParseException * @throws IOException */ @RequestMapping("getWorkOrder") public void getWorkOrder(HttpServletResponse response, HttpServletRequest request, HttpSession session) throws ParseException, IOException { String workOrder = request.getParameter("workOrder"); String rows = request.getParameter("requestRows"); UserModel user = userService.getUserByName("w06804"); user.setRoleName("管理员"); com.alibaba.fastjson.JSONArray requestRows = com.alibaba.fastjson.JSONArray.parseArray(rows); com.alibaba.fastjson.JSONObject workOrderJson = com.alibaba.fastjson.JSONObject.parseObject(workOrder); JSONArray jsonarray=new JSONArray(); WorkOrder wOrder = new WorkOrder(); //wOrder.setWorkOrderId(workOrderJson.get("workOrderId").toString()); wOrder.setWorkOrderName(workOrderJson.get("workOrderName").toString()); wOrder.setExecuteTime(workOrderJson.get("executeTime").toString()); wOrder.setRequestRowFromZH(JSONArray .fromObject(workOrderJson.get("reqRowListFrom")) ); wOrder.setSource(wOrder.source_zh); wOrder.setState(wOrder.state_c); wOrder.setUserName("w06804"); //暂时写死 管理员账号 //处理bfid String uId = user.getId(); String uoId = this.userOrgService.getOrgIdByUser(uId); //String name = this.orgService.getNameById(uoId); String bfId = "BF-ZH"; String time = workOrderJson.get("executeTime").toString().substring(0,10).replace("-",""); String bfTime = "%" + time + "%"; List<WorkOrder> workOrderList = this.workOrderService.isExist(bfTime); if(workOrderList.isEmpty()){//按照日期查询 当天没有数据时num设置为1 wOrder.setNum(1); bfId += "-" + time + "-0001"; }else{//当天存在数据时 找到当天最大的num 并按照num的位数 进行拼接 拼接之后将num的值加1 int numMax = this.workOrderService.getMaxNum(bfTime); int num = numMax + 1; if(num < 10){ bfId += "-" + time + "-000" + num; }else if(num >= 10 && num < 100){ bfId += "-" + time + "-00" + num; }else if(num >= 100 && num < 1000){ bfId += "-" + time + "-0" + num; }else{ bfId += "-" + time + "-" + num; } wOrder.setNum(num); } wOrder.setWorkOrderId(bfId); wOrder.setBfId(""); wOrder.setType(WorkOrder.type_1); //来源为8088推送过来的 wOrder.setBossId(workOrderJson.get("workOrderId").toString()); workOrderService.insertWorkOrderByPush(wOrder); JSONArray json = JSONArray.fromObject(rows); if(json.size()>0){ for(int i=0;i<json.size();i++){ RequestRow requestRow = new RequestRow(); // 遍历 jsonarray 数组,把每一个对象转成 json 对象 JSONObject job = json.getJSONObject(i); // 得到 每个对象中的属性值 requestRow.setServiceType(job.get("serviceType").toString()); //requestRow.setWoId(job.get("woId").toString()); requestRow.setWoId(bfId); requestRow.setPortUse(job.get("portUse").toString()); requestRow.setSourseAddress(job.get("sourseAddress").toString()); requestRow.setDestServerName(job.get("destServerName").toString()); requestRow.setDestPort(job.get("destPort").toString()); requestRow.setDestAddress(job.get("destAddress").toString()); requestRow.setSourseServerName(job.get("sourseServerName").toString()); requestRow.setLinkType(job.get("linkType").toString()); requestRow.setId(job.get("id").toString()); requestRow.setGateWay(job.get("gateway").toString()); requestRow.setFlowType(job.get("flowType").toString()); requestRow.setTimeRange(job.get("timeRange").toString()); requestRowService.insertRequestRow(requestRow); } } policyGenerateService.policyMake(wOrder.getWorkOrderId(),wOrder.getReqRowListFrom(),user); response.getWriter().write("success"); response.getWriter().flush(); response.getWriter().close(); }