1 Star 0 Fork 0

维之/xiweile.github.io

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.html 181.98 KB
一键复制 编辑 原始数据 按行查看 历史
维之 提交于 2019-11-15 16:49 . Site updated: 2019-11-15 16:49:00
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695
<!DOCTYPE html>
<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">
<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">
<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">
<link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">
<meta name="keywords" content="Hexo, NexT">
<meta name="description" content="IT技术文章/JAVA学习分享/个人随笔">
<meta property="og:type" content="website">
<meta property="og:title" content="WeillerBlog">
<meta property="og:url" content="http://weiller.com/index.html">
<meta property="og:site_name" content="WeillerBlog">
<meta property="og:description" content="IT技术文章/JAVA学习分享/个人随笔">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WeillerBlog">
<meta name="twitter:description" content="IT技术文章/JAVA学习分享/个人随笔">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Mist',
version: '5.1.4',
sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
fancybox: true,
tabs: true,
motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="http://weiller.com/">
<title>WeillerBlog</title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container sidebar-position-left
page-home">
<div class="headband"></div>
<!-- 右上角github图标 -->
<a href="https://github.com/xiweile" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<!-- 右上角github图标 -->
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">WeillerBlog</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">惠维乐个人博客</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br>
首页
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags/" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
标签
</a>
</li>
<li class="menu-item menu-item-categories">
<a href="/categories/" rel="section">
<i class="menu-item-icon fa fa-fw fa-th"></i> <br>
分类
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives/" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
归档
</a>
</li>
<li class="menu-item menu-item-about">
<a href="/about/" rel="section">
<i class="menu-item-icon fa fa-fw fa-user"></i> <br>
关于
</a>
</li>
<li class="menu-item menu-item-search">
<a href="javascript:;" class="popup-trigger">
<i class="menu-item-icon fa fa-search fa-fw"></i> <br>
搜索
</a>
</li>
</ul>
<div class="site-search">
<div class="popup search-popup local-search-popup">
<div class="local-search-header clearfix">
<span class="search-icon">
<i class="fa fa-search"></i>
</span>
<span class="popup-btn-close">
<i class="fa fa-times-circle"></i>
</span>
<div class="local-search-input-wrapper">
<input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
</div>
</div>
<div id="local-search-result"></div>
</div>
</div>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<section id="posts" class="posts-expand">
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/11/15/2019-11-15-mybatis-plus代码生成maven插件/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/11/15/2019-11-15-mybatis-plus代码生成maven插件/" itemprop="url">mybatis-plus代码生成maven插件</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-15T10:00:00+08:00">
2019-11-15
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/java/" itemprop="url" rel="index">
<span itemprop="name">java</span>
</a>
</span>
</span>
<span id="/2019/11/15/2019-11-15-mybatis-plus代码生成maven插件/" class="leancloud_visitors" data-flag-title="mybatis-plus代码生成maven插件">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<blockquote>
<p>为了在项目中快捷方便的代码生成,将mybatis-plus-generator封装为了一个maven的插件<code>mybatis-plus-generator-maven-plugin</code>,在要使用的项目pom文件引入该插件,执行mvn命令,即可直接生成代码到项目中,生成基于<code>mybatis-plus</code>的mapper、service、controller三层结构,包括entity实体类和mapper.xml文件,生成后直接能够满足基本的条件查询和分页查询。下面介绍该插件的使用步骤:</p>
</blockquote>
<h2 id="一、下载插件"><a href="#一、下载插件" class="headerlink" title="一、下载插件"></a>一、下载插件</h2><p>方式1:CSDN中下载:jar包地址:<a href="https://download.csdn.net/download/xiweiller/11978432" target="_blank" rel="noopener">mybatis-plus-generator-maven-plugin-1.0.0.jar</a>,pom文件地址:<a href="https://download.csdn.net/download/xiweiller/11978463" target="_blank" rel="noopener">pom.xml</a><br>方式2:将源代码导入项目工程中,执行<code>mvn intall</code>,源码地址:<a href="https://github.com/xiweile/mybatis-plus-generator-maven-plugin" target="_blank" rel="noopener">https://github.com/xiweile/mybatis-plus-generator-maven-plugin</a></p>
<h2 id="二、插件上传至本地仓库"><a href="#二、插件上传至本地仓库" class="headerlink" title="二、插件上传至本地仓库"></a>二、插件上传至本地仓库</h2><p>在下载好的mybatis-plus-generator-maven-plugin-1.0.0.jar和pom.xml文件目录下打开命令行工具,执行下面命令<code>-DpomFile</code>为pom.xml所在目录,<code>-Dfile</code>是jar所在位置,<code>-Dpackaging</code>固定为 maven-plugin,其他参数此处不介绍。<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mvn install:install-file -DpomFile=pom.xml -Dfile=mybatis-plus-generator-maven-plugin-1.0.0.jar -DgroupId=com.weiller -DartifactId=mybatis-plus-generator-maven-plugin -Dversion=1.0.0 -Dpackaging=maven-plugin</span><br></pre></td></tr></table></figure></p>
<h2 id="三、在pom中引入插件"><a href="#三、在pom中引入插件" class="headerlink" title="三、在pom中引入插件"></a>三、在pom中引入插件</h2><p>在要使用插件的工程pom文件中引入该插件,如下案例<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">build</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">plugins</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line"> <span class="comment">&lt;!-- mybatis-plus generator 自动生成代码插件 --&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.weiller<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-plus-generator-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.0.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">configurationFile</span>&gt;</span>$&#123;basedir&#125;/src/main/resources/generator/mp-code-generator-config.yaml<span class="tag">&lt;/<span class="name">configurationFile</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line"> <span class="comment">&lt;!-- mybatis-plus generator 自动生成代码插件 --&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">build</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>注意<code>configurationFile</code>参数为 下一步中配置文件generator-config的位置,该文件类型为<code>yaml</code></p>
<h2 id="四、填写配置文件"><a href="#四、填写配置文件" class="headerlink" title="四、填写配置文件"></a>四、填写配置文件</h2><p>配置完整案例<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">globalConfig:</span></span><br><span class="line"><span class="attr"> author:</span> <span class="string">weiller</span></span><br><span class="line"><span class="attr"> open:</span> <span class="literal">false</span></span><br><span class="line"><span class="attr"> idType:</span> <span class="string">INPUT</span></span><br><span class="line"><span class="attr"> dateType:</span> <span class="string">ONLY_DATE</span></span><br><span class="line"><span class="attr"> enableCache:</span> <span class="literal">false</span></span><br><span class="line"><span class="attr"> activeRecord:</span> <span class="literal">false</span></span><br><span class="line"><span class="attr"> baseResultMap:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr"> baseColumnList:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr"> swagger2:</span> <span class="literal">false</span></span><br><span class="line"><span class="attr"> fileOverride:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">dataSourceConfig:</span></span><br><span class="line"><span class="attr"> url:</span> <span class="attr">jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;useSSL=false&amp;characterEncoding=utf8</span></span><br><span class="line"><span class="attr"> driverName:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr"> username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr"> password:</span> <span class="string">xiweile</span></span><br><span class="line"><span class="attr">packageConfig:</span></span><br><span class="line"><span class="attr"> parent:</span> <span class="string">com.weiller</span></span><br><span class="line"><span class="attr"> moduleName:</span> <span class="string">rest</span></span><br><span class="line"><span class="attr"> entity:</span> <span class="string">model</span></span><br><span class="line"><span class="attr"> service:</span> <span class="string">service</span></span><br><span class="line"><span class="attr"> serviceImpl:</span> <span class="string">service.impl</span></span><br><span class="line"><span class="attr"> mapper:</span> <span class="string">dao</span></span><br><span class="line"><span class="attr"> xml:</span> <span class="string">mapper</span></span><br><span class="line"><span class="attr"> controller:</span> <span class="string">controller</span></span><br><span class="line"><span class="attr"> pathInfo:</span></span><br><span class="line"><span class="attr"> entity_path:</span> <span class="string">src\main\java\com\weiller\rest\model</span></span><br><span class="line"><span class="attr"> service_path:</span> <span class="string">src\main\java\com\weiller\rest\service</span></span><br><span class="line"><span class="attr"> service_impl_path:</span> <span class="string">src\main\java\com\weiller\rest\service\impl</span></span><br><span class="line"><span class="attr"> mapper_path:</span> <span class="string">src\main\java\com\weiller\rest\dao</span></span><br><span class="line"><span class="attr"> xml_path:</span> <span class="string">src\main\resources\com\weiller\rest\mapper</span></span><br><span class="line"><span class="attr"> controller_path:</span> <span class="string">src\main\java\com\weiller\rest\controller</span></span><br><span class="line"><span class="attr">strategyConfig:</span></span><br><span class="line"><span class="attr"> naming:</span> <span class="string">underline_to_camel</span></span><br><span class="line"><span class="attr"> columnNaming:</span> <span class="string">underline_to_camel</span></span><br><span class="line"><span class="attr"> entityLombokModel:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr"> superMapperClass:</span> <span class="string">com.baomidou.mybatisplus.core.mapper.BaseMapper</span></span><br><span class="line"><span class="attr"> superServiceClass:</span> <span class="string">com.baomidou.mybatisplus.extension.service.IService</span></span><br><span class="line"><span class="attr"> superServiceImplClass:</span> <span class="string">com.baomidou.mybatisplus.extension.service.impl.ServiceImpl</span></span><br><span class="line"><span class="attr"> controllerMappingHyphenStyle:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr"> restControllerStyle:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr"> tablePrefix:</span></span><br><span class="line"><span class="attr"> include:</span></span><br><span class="line"><span class="bullet"> -</span> <span class="string">t_user</span></span><br></pre></td></tr></table></figure></p>
<p>配置项参数解释:<a href="https://mp.baomidou.com/config/generator-config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE" target="_blank" rel="noopener">https://mp.baomidou.com/config/generator-config.html#基本配置</a></p>
<h2 id="五、运行maven命令"><a href="#五、运行maven命令" class="headerlink" title="五、运行maven命令"></a>五、运行maven命令</h2><p>在命令工具中,进入到要生成项目的根目录(即pom.xml目录),执行以下命令<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mvn mybatis-plus-generator:generator</span><br></pre></td></tr></table></figure></p>
<p>如果是使用InterlliJ IDEA工具,使用更加方便,步骤如下图:<br><img src="https://img-blog.csdnimg.cn/20191115153431762.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>生成结果如下:</p>
<p><img src="https://img-blog.csdnimg.cn/20191115152720828.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/15/2019-09-15-Java设计模式:静态代理、JDK动态代理和cglib动态代理/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/15/2019-09-15-Java设计模式:静态代理、JDK动态代理和cglib动态代理/" itemprop="url">Java设计模式:静态代理、JDK动态代理和cglib动态代理</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-15T10:00:00+08:00">
2019-09-15
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/java/" itemprop="url" rel="index">
<span itemprop="name">java</span>
</a>
</span>
</span>
<span id="/2019/09/15/2019-09-15-Java设计模式:静态代理、JDK动态代理和cglib动态代理/" class="leancloud_visitors" data-flag-title="Java设计模式:静态代理、JDK动态代理和cglib动态代理">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line">静态代理、JDK动态代理和cglib动态代理</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 静态代理案例:增强猫(Cat的代理类)</span></span><br><span class="line"><span class="comment"> * 利用装饰者模式</span></span><br><span class="line"><span class="comment"> * 要求:1.委托类、代理类必须实现共同的接口 2.代理类需要获得委托类的对象的引用</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> weiller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0,2016-11-27 14:11:36</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StaticProxyDemo</span> <span class="keyword">implements</span> <span class="title">Jump</span></span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/** 委托类对象 */</span></span><br><span class="line"> <span class="keyword">private</span> Cat cat;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/** 委托类对象作为参数传入构造方法 */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">StaticProxyDemo</span><span class="params">(Cat cat)</span></span>&#123;</span><br><span class="line"> <span class="keyword">this</span>.cat = cat;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">jump</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 增强功能</span></span><br><span class="line"> System.out.println(<span class="string">"准备起跳..."</span>);</span><br><span class="line"> <span class="comment">// 原始方法调用</span></span><br><span class="line"> cat.jump();</span><br><span class="line"> <span class="comment">// 增强功能</span></span><br><span class="line"> System.out.println(<span class="string">"回落..."</span>);</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * JDC动态代理案例</span></span><br><span class="line"><span class="comment"> * 要求:目标类必须实现一个接口</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> weiller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0,2016-11-27 08:34:05</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JDKProxyDemo</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获得代理对象</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> t 目标类对象实现的接口</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 代理对象</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span>&lt;T&gt; T <span class="title">createProxyObject</span><span class="params">(T t)</span></span>&#123;</span><br><span class="line"> <span class="comment">// 5.将被代理的对象修饰为final,便于匿名内部类使用</span></span><br><span class="line"> <span class="keyword">final</span> Object obj = t;</span><br><span class="line"> <span class="comment">// 2.获取被代理对象的类加载器</span></span><br><span class="line"> ClassLoader loader = t.getClass().getClassLoader();</span><br><span class="line"> <span class="comment">// 3.获取被代理对象的所有实现接口 </span></span><br><span class="line"> Class&lt;?&gt;[] interfaces = t.getClass().getInterfaces();</span><br><span class="line"> <span class="comment">// 4.创建调用处理对象</span></span><br><span class="line"> InvocationHandler h = <span class="keyword">new</span> InvocationHandler() &#123;</span><br><span class="line"> </span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span></span></span><br><span class="line"><span class="function"> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line"> <span class="comment">// 7.增强功能</span></span><br><span class="line"> System.out.println(<span class="string">"开启事务..."</span>);</span><br><span class="line"> <span class="comment">// 6.原始方法调用</span></span><br><span class="line"> Object ret = method.invoke(obj, args);</span><br><span class="line"> <span class="comment">// 增强功能</span></span><br><span class="line"> System.out.println(<span class="string">"关闭事务..."</span>);</span><br><span class="line"> <span class="keyword">return</span> ret;</span><br><span class="line"> &#125;</span><br><span class="line"> &#125;;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 1.创建代理对象</span></span><br><span class="line"> T proxyObject = (T) Proxy.newProxyInstance(loader, interfaces, h);</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">return</span> proxyObject;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * cglib动态代理案例</span></span><br><span class="line"><span class="comment"> * cglib是针对类来实现代理的,他的原理是对指定的目标类生成一个子类,并覆盖其中方法实现增强。</span></span><br><span class="line"><span class="comment"> * 要求:CGLib由于是采用动态创建子类的方法,对于final方法,无法进行代理。</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> weiller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> 1.0,2016-11-27 09:28:11</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibPorxyDemo</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="function"><span class="keyword">public</span> T <span class="title">createProxyObject</span><span class="params">(Class clazz)</span></span>&#123;</span><br><span class="line"> <span class="comment">// 1.在内存中创建动态的增强类</span></span><br><span class="line"> Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line"> <span class="comment">// 2.为该增强类设置父类,与目标类形成继承关系。此类最终完成对原始方法的功能,同时对其功能进行加强。</span></span><br><span class="line"> enhancer.setSuperclass(clazz);</span><br><span class="line"> <span class="comment">// 3.创建回调处理对象,对目标类的方法进行拦截</span></span><br><span class="line"> Callback callback = <span class="keyword">new</span> MethodInterceptor() &#123;</span><br><span class="line"> </span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * obj:目标类的实例</span></span><br><span class="line"><span class="comment"> * method:被拦截的方法对象</span></span><br><span class="line"><span class="comment"> * args:调用参数</span></span><br><span class="line"><span class="comment"> * methodProxy:代理方法的对象(通过JDK代理得到)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object obj, Method method, Object[] args,</span></span></span><br><span class="line"><span class="function"><span class="params"> MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line"> <span class="comment">// 增强功能</span></span><br><span class="line"> System.out.println(<span class="string">"说相声..."</span>);</span><br><span class="line"> <span class="comment">//System.out.println(obj); // 调用obj产生死循环,溢栈。</span></span><br><span class="line"> <span class="comment">// 利用代理方法对象调用原始方法。注意:不能调用invoke()方法,否则产生死循环,溢栈。无法进行代理</span></span><br><span class="line"> <span class="comment">// 代理是通过多态的形式进行的。</span></span><br><span class="line"> Object ret = methodProxy.invokeSuper(obj, args);</span><br><span class="line"> <span class="keyword">return</span> ret;</span><br><span class="line"> &#125;</span><br><span class="line"> &#125;;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 4.设置回调</span></span><br><span class="line"> enhancer.setCallback(callback);</span><br><span class="line"> <span class="comment">// 5.通过字节码技术动态创建该增强类的实例</span></span><br><span class="line"> T newObject = (T) enhancer.create();</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">return</span> newObject;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/13/2019-09-13-springcloud-zuul实践:自定义异常过滤器,统一异常响应格式/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/13/2019-09-13-springcloud-zuul实践:自定义异常过滤器,统一异常响应格式/" itemprop="url">springcloud zuul实践:自定义异常过滤器,统一异常响应格式</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-13T10:00:00+08:00">
2019-09-13
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/springcloud/" itemprop="url" rel="index">
<span itemprop="name">springcloud</span>
</a>
</span>
</span>
<span id="/2019/09/13/2019-09-13-springcloud-zuul实践:自定义异常过滤器,统一异常响应格式/" class="leancloud_visitors" data-flag-title="springcloud zuul实践:自定义异常过滤器,统一异常响应格式">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>在springcloud项目中,网关发生异常时,响应内容并不是我们想要的格式,内容如下:<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line"> <span class="attr">"timestamp"</span>: <span class="number">1481674980376</span>,</span><br><span class="line"> <span class="attr">"status"</span>: <span class="number">500</span>,</span><br><span class="line"> <span class="attr">"error"</span>: <span class="string">"Internal Server Error"</span>,</span><br><span class="line"> <span class="attr">"exception"</span>: <span class="string">"java.lang.RuntimeException"</span>,</span><br><span class="line"> <span class="attr">"message"</span>: <span class="string">"Exist some errors..."</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面的json则是内置异常过滤器封装的一种格式。我们现在想要修改她,就需要自定义异常过滤器。 </p>
<ul>
<li>首先继承抽象类<code>ZuulFilter</code>,实现<code>filterType()</code><code>filterOrder()</code><code>shouldFilter()</code><code>run()</code>四个抽象方法。前三个方法均使用父方法逻辑。仅修改<code>run()</code>中部分内容,主体逻辑步骤依然参考<code>SendErrorFilter</code></li>
<li>方法<code>run()</code>中重新定义异常响应格式,将自定义的响应体,设置到原有的响应中。</li>
<li>停用内置的默认异常处理器<code>SendErrorFilter</code>,在application.yml中设置<code>zuul.SendErrorFilter.error.disable: true</code></li>
<li><code>CustomSendErrorFilter</code>在内置的默认异常处理器失效时生效。设置注解<code>ConditionalOnProperty</code>属性name=<code>&quot;zuul.SendErrorFilter.error.disable&quot;</code></li>
</ul>
<p>过滤器详细介绍可参考往期文章:<a href="https://blog.csdn.net/xiweiller/article/details/100772775" target="_blank" rel="noopener">springcloud zuul源码分析:内置过滤器</a></p>
<p>下面是案例代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@ConditionalOnProperty</span>(name=<span class="string">"zuul.SendErrorFilter.error.disable"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomSendErrorFilter</span> <span class="keyword">extends</span> <span class="title">SendErrorFilter</span> </span>&#123;</span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">filterType</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">super</span>.filterType();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">filterOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">super</span>.filterOrder();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">super</span>.shouldFilter();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"> RequestContext ctx = RequestContext.getCurrentContext();</span><br><span class="line"> HttpServletResponse response = ctx.getResponse();</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> <span class="keyword">int</span> responseStatusCode = ctx.getResponseStatusCode();</span><br><span class="line"> <span class="comment">// 此处自定义响应体start</span></span><br><span class="line"> String cumstomBody = <span class="string">"&#123;&#125;"</span>;<span class="comment">//内容省略...</span></span><br><span class="line"> <span class="comment">// 此处自定义响应体end</span></span><br><span class="line"> response.setStatus(ctx.getResponseStatusCode());</span><br><span class="line"> response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);</span><br><span class="line"> response.getOutputStream().write(cumstomBody.getBytes());</span><br><span class="line"> &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line"> ReflectionUtils.rethrowRuntimeException(e);</span><br><span class="line"> &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line"> ThreadLocalUtil.remove();</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/11/2019-09-17-springcloud-zuul实践:自定义前置过滤器进行权限认证/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/11/2019-09-17-springcloud-zuul实践:自定义前置过滤器进行权限认证/" itemprop="url">springcloud zuul实践:自定义前置过滤器进行权限认证</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-11T10:00:00+08:00">
2019-09-11
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/springcloud/" itemprop="url" rel="index">
<span itemprop="name">springcloud</span>
</a>
</span>
</span>
<span id="/2019/09/11/2019-09-17-springcloud-zuul实践:自定义前置过滤器进行权限认证/" class="leancloud_visitors" data-flag-title="springcloud zuul实践:自定义前置过滤器进行权限认证">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>在springcloud项目中,权限认证逻辑一般放在请求路由之前,如果认证通过,则会执行route类型的过滤器,访问微服务获取数据。如果认证未通过,则要设置不进行路由,从而直接响应给客户端。</p>
<p>过滤器详细介绍可参考往期文章:<a href="https://blog.csdn.net/xiweiller/article/details/100772775" target="_blank" rel="noopener">springcloud zuul源码分析:内置过滤器</a></p>
<p>因此,我们通过自定义一个前置过滤器,来实现权限认证的逻辑。</p>
<ul>
<li>首先继承抽象类<code>ZuulFilter</code>,实现<code>filterType()</code><code>filterOrder()</code><code>shouldFilter()</code><code>run()</code>四个抽象方法。</li>
<li><code>filterType()</code> 返回 <code>&quot;pre&quot;</code>定义过滤器为前置过滤器。</li>
<li>方法<code>run()</code>中是执行逻辑,<code>RequestContext.getCurrentContext()</code>获取当前上下文实例<code>ctx</code>,如果认证不通过,可设置<code>ctx.setSendZuulResponse(false)</code>阻止请求进行路由。</li>
<li>前置过滤器内也可以对请求参数进行修改或添加。</li>
</ul>
<p>下面是案例代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AccessFilter</span> <span class="keyword">extends</span> <span class="title">ZuulFilter</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型: </span></span><br><span class="line"><span class="comment"> * pre:可以在请求被路由之前调用</span></span><br><span class="line"><span class="comment"> * route:在路由请求时候被调用 </span></span><br><span class="line"><span class="comment"> * post:在route和error过滤器之后被调用 </span></span><br><span class="line"><span class="comment"> * error:处理请求时发生错误时被调用</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">filterType</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="string">"pre"</span>; <span class="comment">// 前置过滤器</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">filterOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="number">2</span>; <span class="comment">// 过滤器的执行顺序,数字越大优先级越低</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">true</span>;<span class="comment">// 是否执行该过滤器,此处为true,说明需要过滤</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> RequestContext ctx = RequestContext.getCurrentContext();</span><br><span class="line"> HttpServletRequest request = ctx.getRequest();</span><br><span class="line"> HttpServletResponse response = ctx.getResponse();</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 访问权限认证逻辑</span></span><br><span class="line"> <span class="keyword">boolean</span> result = <span class="keyword">this</span>.exeAuth(request);</span><br><span class="line"> <span class="keyword">if</span>(result ==<span class="keyword">true</span>)&#123;<span class="comment">//通过校验</span></span><br><span class="line"> <span class="comment">// 添加额外的请求参数为可选逻辑...</span></span><br><span class="line"> <span class="comment">// 添加额外的请求参数start</span></span><br><span class="line"> Map&lt;String, List&lt;String&gt;&gt; requestQueryParams = ctx.getRequestQueryParams();</span><br><span class="line"> List&lt;String&gt; params = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line"> params.add(<span class="string">"otherParamValue"</span>);</span><br><span class="line"> requestQueryParams.put(<span class="string">"otherParamKey"</span>,params);</span><br><span class="line"> ctx.setRequestQueryParams(requestQueryParams);</span><br><span class="line"> <span class="comment">// 添加额外的请求参数end</span></span><br><span class="line"> </span><br><span class="line"> &#125;<span class="keyword">else</span>&#123;<span class="comment">//校验未通过</span></span><br><span class="line"> ctx.setSendZuulResponse(<span class="keyword">false</span>); <span class="comment">// 过滤该请求,不进行路由</span></span><br><span class="line"> ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());</span><br><span class="line"> ctx.setResponseBody(JSON.toJSONString(res)); <span class="comment">// 返回前端内容</span></span><br><span class="line"> response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 认证逻辑</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ZuulException</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">exeAuth</span><span class="params">(HttpServletRequest request)</span></span>&#123;</span><br><span class="line"> <span class="comment">// 详细认证逻辑...</span></span><br><span class="line"> <span class="comment">// 省略...</span></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/11/2019-09-11-springcloud-zuul实践:自定义前置过滤器进行权限认证/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/11/2019-09-11-springcloud-zuul实践:自定义前置过滤器进行权限认证/" itemprop="url">springcloud zuul实践:自定义前置过滤器进行权限认证</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-11T10:00:00+08:00">
2019-09-11
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/springcloud/" itemprop="url" rel="index">
<span itemprop="name">springcloud</span>
</a>
</span>
</span>
<span id="/2019/09/11/2019-09-11-springcloud-zuul实践:自定义前置过滤器进行权限认证/" class="leancloud_visitors" data-flag-title="springcloud zuul实践:自定义前置过滤器进行权限认证">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>在springcloud项目中,权限认证逻辑一般放在请求路由之前,如果认证通过,则会执行route类型的过滤器,访问微服务获取数据。如果认证未通过,则要设置不进行路由,从而直接响应给客户端。</p>
<p>过滤器详细介绍可参考往期文章:<a href="https://blog.csdn.net/xiweiller/article/details/100772775" target="_blank" rel="noopener">springcloud zuul源码分析:内置过滤器</a></p>
<p>因此,我们通过自定义一个前置过滤器,来实现权限认证的逻辑。</p>
<ul>
<li>首先继承抽象类<code>ZuulFilter</code>,实现<code>filterType()</code><code>filterOrder()</code><code>shouldFilter()</code><code>run()</code>四个抽象方法。</li>
<li><code>filterType()</code> 返回 <code>&quot;pre&quot;</code>定义过滤器为前置过滤器。</li>
<li>方法<code>run()</code>中是执行逻辑,<code>RequestContext.getCurrentContext()</code>获取当前上下文实例<code>ctx</code>,如果认证不通过,可设置<code>ctx.setSendZuulResponse(false)</code>阻止请求进行路由。</li>
<li>前置过滤器内也可以对请求参数进行修改或添加。</li>
</ul>
<p>下面是案例代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AccessFilter</span> <span class="keyword">extends</span> <span class="title">ZuulFilter</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型: </span></span><br><span class="line"><span class="comment"> * pre:可以在请求被路由之前调用</span></span><br><span class="line"><span class="comment"> * route:在路由请求时候被调用 </span></span><br><span class="line"><span class="comment"> * post:在route和error过滤器之后被调用 </span></span><br><span class="line"><span class="comment"> * error:处理请求时发生错误时被调用</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">filterType</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="string">"pre"</span>; <span class="comment">// 前置过滤器</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">filterOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="number">2</span>; <span class="comment">// 过滤器的执行顺序,数字越大优先级越低</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">shouldFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">true</span>;<span class="comment">// 是否执行该过滤器,此处为true,说明需要过滤</span></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> RequestContext ctx = RequestContext.getCurrentContext();</span><br><span class="line"> HttpServletRequest request = ctx.getRequest();</span><br><span class="line"> HttpServletResponse response = ctx.getResponse();</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 访问权限认证逻辑</span></span><br><span class="line"> <span class="keyword">boolean</span> result = <span class="keyword">this</span>.exeAuth(request);</span><br><span class="line"> <span class="keyword">if</span>(result ==<span class="keyword">true</span>)&#123;<span class="comment">//通过校验</span></span><br><span class="line"> <span class="comment">// 添加额外的请求参数为可选逻辑...</span></span><br><span class="line"> <span class="comment">// 添加额外的请求参数start</span></span><br><span class="line"> Map&lt;String, List&lt;String&gt;&gt; requestQueryParams = ctx.getRequestQueryParams();</span><br><span class="line"> List&lt;String&gt; params = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line"> params.add(<span class="string">"otherParamValue"</span>);</span><br><span class="line"> requestQueryParams.put(<span class="string">"otherParamKey"</span>,params);</span><br><span class="line"> ctx.setRequestQueryParams(requestQueryParams);</span><br><span class="line"> <span class="comment">// 添加额外的请求参数end</span></span><br><span class="line"> </span><br><span class="line"> &#125;<span class="keyword">else</span>&#123;<span class="comment">//校验未通过</span></span><br><span class="line"> ctx.setSendZuulResponse(<span class="keyword">false</span>); <span class="comment">// 过滤该请求,不进行路由</span></span><br><span class="line"> ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());</span><br><span class="line"> ctx.setResponseBody(JSON.toJSONString(res)); <span class="comment">// 返回前端内容</span></span><br><span class="line"> response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 认证逻辑</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> ZuulException</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">exeAuth</span><span class="params">(HttpServletRequest request)</span></span>&#123;</span><br><span class="line"> <span class="comment">// 详细认证逻辑...</span></span><br><span class="line"> <span class="comment">// 省略...</span></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/10/2019-09-10-springcloud zuul源码分析:内置过滤器/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/10/2019-09-10-springcloud zuul源码分析:内置过滤器/" itemprop="url">springcloud zuul源码分析:内置过滤器</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-10T15:00:00+08:00">
2019-09-10
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/springcloud/" itemprop="url" rel="index">
<span itemprop="name">springcloud</span>
</a>
</span>
</span>
<span id="/2019/09/10/2019-09-10-springcloud zuul源码分析:内置过滤器/" class="leancloud_visitors" data-flag-title="springcloud zuul源码分析:内置过滤器">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>springcloud项目中我们常常使用zuul作为网关,用它做一些路由分发、权限校验、统一异常处理、日志收集等等工作。而实现这些功能的重要组件就是它的过滤器<code>ZuulFilter</code>,本篇文章介绍zuul中内置过滤器。</p>
<h3 id="1-ZuulFilter介绍"><a href="#1-ZuulFilter介绍" class="headerlink" title="1.ZuulFilter介绍"></a>1.ZuulFilter介绍</h3><p>我们自定义的每个过滤器都需要继承ZuulFilter才能被加载生效。它有四个重要的抽象方法需要重写。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> String <span class="title">filterType</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">int</span> <span class="title">filterOrder</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">shouldFilter</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="function">Object <span class="title">run</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure></p>
<p>四个方法介绍:</p>
<ul>
<li><code>filterType</code> 返回值标识过滤器类型。<ul>
<li><code>pre</code> 在请求被路由之前调用。</li>
<li><code>routing</code> 路由时被调用。</li>
<li><code>post</code> 在routing或error过滤器之后被调用。</li>
<li><code>error</code> 在请求发送异常时被调用。</li>
</ul>
</li>
<li><code>filterOrder</code> 返回int值标识过滤器执行顺序,数值越小优先级越高。</li>
<li><code>shouldFilter</code> 返回boolean类型确定是否执行该过滤器。</li>
</ul>
<h3 id="2-内置过滤器介绍"><a href="#2-内置过滤器介绍" class="headerlink" title="2.内置过滤器介绍"></a>2.内置过滤器介绍</h3><h4 id="1)按filterType分类图示"><a href="#1)按filterType分类图示" class="headerlink" title="1)按filterType分类图示"></a>1)按filterType分类图示</h4><p><img src="https://img-blog.csdnimg.cn/20190912154343155.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="zuul核心过滤器按filterType分类"></p>
<h4 id="2)各过滤器功能详细介绍"><a href="#2)各过滤器功能详细介绍" class="headerlink" title="2)各过滤器功能详细介绍"></a>2)各过滤器功能详细介绍</h4><h5 id="pre过滤器"><a href="#pre过滤器" class="headerlink" title="pre过滤器"></a>pre过滤器</h5><ul>
<li><code>ServletDetectionFilter</code>:它的执行顺序为-3,是最先被执行的过滤器。该过滤器总是会被执行,主要用来检测当前请求是通过Spring的DispatcherServlet处理运行,还是通过ZuulServlet来处理运行的。它的检测结果会以布尔类型保存在当前请求上下文的<code>isDispatcherServletRequest</code>参数中,这样在后续的过滤器中,我们就可以通过<code>RequestUtils.isDispatcherServletRequest()</code><code>RequestUtils.isZuulServletRequest()</code>方法判断它以实现做不同的处理。一般情况下,发送到API网关的外部请求都会被Spring的DispatcherServlet处理,除了通过/zuul/路径访问的请求会绕过DispatcherServlet,被ZuulServlet处理,主要用来应对处理大文件上传的情况。另外,对于ZuulServlet的访问路径/zuul/,我们可以通过<code>zuul.servletPath</code>参数来进行修改。</li>
<li><code>Servlet30WrapperFilter</code>:它的执行顺序为-2,是第二个执行的过滤器。目前的实现会对所有请求生效,主要为了将原始的HttpServletRequest包装成Servlet30RequestWrapper对象。</li>
<li><code>FormBodyWrapperFilter</code>:它的执行顺序为-1,是第三个执行的过滤器。该过滤器仅对两种类请求生效,第一类是Content-Type为<code>application/x-www-form-urlencoded</code>的请求,第二类是Content-Type为<code>multipart/form-data</code>并且是由Spring的DispatcherServlet处理的请求(用到了ServletDetectionFilter的处理结果)。而该过滤器的主要目的是将符合要求的请求体包装成FormBodyRequestWrapper对象。</li>
<li><code>DebugFilter</code>:它的执行顺序为1,是第四个执行的过滤器。该过滤器会根据配置参数<code>zuul.debug.request</code>和请求中的debug参数来决定是否执行过滤器中的操作。而它的具体操作内容则是将当前的请求上下文中的<code>debugRouting</code><code>debugRequest</code>参数设置为true。由于在同一个请求的不同生命周期中,都可以访问到这两个值,所以我们在后续的各个过滤器中可以利用这两值来定义一些debug信息,这样当线上环境出现问题的时候,可以通过请求参数的方式来激活这些debug信息以帮助分析问题。另外,对于请求参数中的debug参数,我们也可以通过<code>zuul.debug.parameter</code>来进行自定义。</li>
<li><code>PreDecorationFilter</code>:它的执行顺序为5,是pre阶段最后被执行的过滤器。该过滤器会判断当前请求上下文中是否存在<code>forward.to</code><code>serviceId</code>参数,如果都不存在,那么它就会执行具体过滤器的操作(如果有一个存在的话,说明当前请求已经被处理过了,因为这两个信息就是根据当前请求的路由信息加载进来的)。而它的具体操作内容就是为当前请求做一些预处理,比如:进行路由规则的匹配、在请求上下文中设置该请求的基本信息以及将路由匹配结果等一些设置信息等,这些信息将是后续过滤器进行处理的重要依据,我们可以通过<code>RequestContext.getCurrentContext()</code>来访问这些信息。另外,我们还可以在该实现中找到一些对HTTP头请求进行处理的逻辑,其中包含了一些耳熟能详的头域,比如:<code>X-Forwarded-Host</code><code>X-Forwarded-Port</code>。另外,对于这些头域的记录是通过zuul.addProxyHeaders参数进行控制的,而这个参数默认值为true,所以Zuul在请求跳转时默认地会为请求增加X-Forwarded-*头域,包括:<code>X-Forwarded-Host</code><code>X-Forwarded-Port</code><code>X-Forwarded-For</code><code>X-Forwarded-Prefix</code><code>X-Forwarded-Proto</code>。我们也可以通过设置<code>zuul.addProxyHeaders=false</code>关闭对这些头域的添加动作。</li>
</ul>
<h5 id="route过滤器"><a href="#route过滤器" class="headerlink" title="route过滤器"></a>route过滤器</h5><ul>
<li><code>RibbonRoutingFilter</code>:它的执行顺序为10,是route阶段第一个执行的过滤器。该过滤器只对请求上下文中存在serviceId参数的请求进行处理,即只对通过<code>serviceId</code>配置路由规则的请求生效。而该过滤器的执行逻辑就是面向服务路由的核心,它通过使用Ribbon和Hystrix来向服务实例发起请求,并将服务实例的请求结果返回。</li>
<li><code>SimpleHostRoutingFilter</code>:它的执行顺序为100,是route阶段第二个执行的过滤器。该过滤器只对请求上下文中存在<code>routeHost</code>参数的请求进行处理,即只对通过url配置路由规则的请求生效。而该过滤器的执行逻辑就是直接向routeHost参数的物理地址发起请求,从源码中我们可以知道该请求是直接通过<code>httpclient</code>包实现的,而没有使用<code>Hystrix</code>命令进行包装,所以这类请求并没有线程隔离和断路器的保护。</li>
<li><code>SendForwardFilter</code>:它的执行顺序为500,是route阶段第三个执行的过滤器。该过滤器只对请求上下文中存在<code>forward.to</code>参数的请求进行处理,即用来处理路由规则中的forward本地跳转配置。<h5 id="post过滤器"><a href="#post过滤器" class="headerlink" title="post过滤器"></a>post过滤器</h5></li>
<li><code>SendErrorFilter</code>:它的执行顺序为0,是post阶段第一个执行的过滤器。该过滤器仅在请求上下文中包含<code>error.status_code</code>参数(由之前执行的过滤器设置的错误编码)并且还没有被该过滤器处理过的时候执行。而该过滤器的具体逻辑就是利用请求上下文中的错误信息来组织成一个forward到API网关<code>/error</code>错误端点的请求来产生错误响应。</li>
<li><code>SendResponseFilter</code>:它的执行顺序为1000,是post阶段最后执行的过滤器。该过滤器会检查请求上下文中是否包含请求响应相关的头信息、响应数据流或是响应体,只有在包含它们其中一个的时候就会执行处理逻辑。而该过滤器的处理逻辑就是利用请求上下文的响应信息来组织需要发送回客户端的响应内容。</li>
</ul>
<h3 id="网关过滤器执行逻辑"><a href="#网关过滤器执行逻辑" class="headerlink" title="网关过滤器执行逻辑"></a>网关过滤器执行逻辑</h3><p>源码逻辑<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ZuulServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line"> <span class="keyword">private</span> ZuulRunner zuulRunner;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">ZuulServlet</span><span class="params">()</span> </span>&#123;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">(ServletConfig config)</span> <span class="keyword">throws</span> ServletException </span>&#123;</span><br><span class="line"> <span class="keyword">super</span>.init(config);</span><br><span class="line"> String bufferReqsStr = config.getInitParameter(<span class="string">"buffer-requests"</span>);</span><br><span class="line"> <span class="keyword">boolean</span> bufferReqs = bufferReqsStr != <span class="keyword">null</span> &amp;&amp; bufferReqsStr.equals(<span class="string">"true"</span>);</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner = <span class="keyword">new</span> ZuulRunner(bufferReqs);</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">service</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line"> <span class="comment">// 省略.... </span></span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> <span class="keyword">this</span>.preRoute();</span><br><span class="line"> &#125; <span class="keyword">catch</span> (ZuulException var13) &#123;</span><br><span class="line"> <span class="keyword">this</span>.error(var13);</span><br><span class="line"> <span class="keyword">this</span>.postRoute();</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> <span class="keyword">this</span>.route();</span><br><span class="line"> &#125; <span class="keyword">catch</span> (ZuulException var12) &#123;</span><br><span class="line"> <span class="keyword">this</span>.error(var12);</span><br><span class="line"> <span class="keyword">this</span>.postRoute();</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> <span class="keyword">this</span>.postRoute();</span><br><span class="line"> &#125; <span class="keyword">catch</span> (ZuulException var11) &#123;</span><br><span class="line"> <span class="keyword">this</span>.error(var11);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">// 省略.... </span></span><br><span class="line"> &#125; </span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">postRoute</span><span class="params">()</span> <span class="keyword">throws</span> ZuulException </span>&#123;</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner.postRoute();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">route</span><span class="params">()</span> <span class="keyword">throws</span> ZuulException </span>&#123;</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner.route();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">preRoute</span><span class="params">()</span> <span class="keyword">throws</span> ZuulException </span>&#123;</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner.preRoute();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">init</span><span class="params">(HttpServletRequest servletRequest, HttpServletResponse servletResponse)</span> </span>&#123;</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner.init(servletRequest, servletResponse);</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">void</span> <span class="title">error</span><span class="params">(ZuulException e)</span> </span>&#123;</span><br><span class="line"> RequestContext.getCurrentContext().setThrowable(e);</span><br><span class="line"> <span class="keyword">this</span>.zuulRunner.error();</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>流程分析</strong><br>请求经ZuulServlet 进入内部service处理方法,依次经过preRoute,route,postRoute三组过滤器,如果任何一个过滤器中发生异常都会转发到error过滤器,而error最终也会再次将结果转发postRoute,有postRoute负责将结果给返回客户端。</p>
<p>执行流程图如下:<br><img src="https://img-blog.csdnimg.cn/20190912162242650.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/" itemprop="url">在线HTML页面导出pdf或图片,支持模拟跳过登陆验证</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-10T10:00:00+08:00">
2019-09-10
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/java/" itemprop="url" rel="index">
<span itemprop="name">java</span>
</a>
</span>
</span>
<span id="/2019/09/10/2019-09-10-在线HTML页面导出pdf或图片,支持模拟跳过登陆验证/" class="leancloud_visitors" data-flag-title="在线HTML页面导出pdf或图片,支持模拟跳过登陆验证">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>项目经常用到把当前页面导出为pdf,或者生成某个页面或部分的快照。如果是简单的页面快照,不没有太多的渲染,可以用<code>html2canvas.min.js</code>导出图片或者<code>html2pdf.bundle.min.js</code>导出为pdf,仅仅在前端就可以完成。但是复杂的页面,以上的导出效果不好,质量也不高。因此我采用<code>PhantomJS</code>,用后台生成pdf、png等进行导出。</p>
<h3 id="1-PhantomJS简介"><a href="#1-PhantomJS简介" class="headerlink" title="1.PhantomJS简介"></a>1.PhantomJS简介</h3><blockquote>
<p>PhantomJS是一个基于webkit的JavaScript API。它使用QtWebKit作为它核心浏览器的功能,使用webkit来编译解释执行JavaScript代码。任何你可以在基于webkit浏览器做的事情,它都能做到。它不仅是个隐形的浏览器,提供了诸如CSS选择器、支持Web标准、DOM操作、JSON、HTML5、Canvas、SVG等,同时也提供了处理文件I/O的操作,从而使你可以向操作系统读写文件等。PhantomJS的用处可谓非常广泛,诸如网络监测、网页截屏、无需浏览器的 Web 测试、页面访问自动化等。</p>
</blockquote>
<h3 id="2-下载及安装"><a href="#2-下载及安装" class="headerlink" title="2.下载及安装"></a>2.下载及安装</h3><p>官方下载地址:<a href="http://phantomjs.org/download.html" target="_blank" rel="noopener">http://phantomjs.org/download.html</a>。目前官方支持三种操作系统,包括windows\Mac OS\Linux这三大主流的环境。根据运行环境选择要下载的包,下面以Windows7为例,我将phantomjs文件放置到D盘根目录下,里面的内容如下图。</p>
<p><img src="../images/java/phantomjs目录截图.jpg" alt="image"></p>
<h3 id="3-如何使用"><a href="#3-如何使用" class="headerlink" title="3.如何使用"></a>3.如何使用</h3><h4 id="1-准备一个配置的js文件"><a href="#1-准备一个配置的js文件" class="headerlink" title="1) 准备一个配置的js文件"></a>1) 准备一个配置的js文件</h4><p>在D盘phantomjs目录下新建一个<code>html2pdf.js</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * phantomJs 脚本 html转图片</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> page = <span class="built_in">require</span>(<span class="string">'webpage'</span>).create(),</span><br><span class="line"> system = <span class="built_in">require</span>(<span class="string">'system'</span>), </span><br><span class="line"> address, output, size,JSESSIONID,domain;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (system.args.length &lt; <span class="number">3</span> || system.args.length &gt; <span class="number">5</span>) &#123;</span><br><span class="line"> phantom.exit(<span class="number">1</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line"> </span><br><span class="line"> address = system.args[<span class="number">1</span>];</span><br><span class="line"> output = system.args[<span class="number">2</span>];</span><br><span class="line"> <span class="keyword">if</span>(system.args.length&gt;<span class="number">3</span>)&#123;</span><br><span class="line"> JSESSIONID = system.args[<span class="number">3</span>];</span><br><span class="line"> domain = system.args[<span class="number">4</span>];</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 添加cookie</span></span><br><span class="line"> phantom.addCookie(&#123;</span><br><span class="line"> <span class="string">"name"</span>:<span class="string">"JSESSIONID"</span>,</span><br><span class="line"> <span class="string">"value"</span>:JSESSIONID,</span><br><span class="line"> <span class="string">"domain"</span>:domain, </span><br><span class="line"> <span class="string">"path"</span>:<span class="string">"/"</span>,</span><br><span class="line"> <span class="string">"httponly"</span>:<span class="literal">false</span>,</span><br><span class="line"> <span class="string">"secure"</span>:<span class="literal">false</span>,</span><br><span class="line"> <span class="string">"expires"</span>: <span class="string">"Fri, 01 Jan 2038 00:00:00 GMT"</span></span><br><span class="line"> &#125;);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">//定义浏览器宽高</span></span><br><span class="line"> page.viewportSize = &#123;</span><br><span class="line"> width : <span class="number">2048</span>,</span><br><span class="line"> height : <span class="number">768</span></span><br><span class="line"> &#125;; </span><br><span class="line"></span><br><span class="line"> <span class="comment">// 纸张尺寸</span></span><br><span class="line"> page.paperSize = &#123;</span><br><span class="line"> format: <span class="string">'A3'</span>,</span><br><span class="line"> orientation: <span class="string">'landscape'</span>,<span class="comment">//横向</span></span><br><span class="line"> margin: &#123; </span><br><span class="line"> left:<span class="string">"2cm"</span>, </span><br><span class="line"> right:<span class="string">"2cm"</span>, </span><br><span class="line"> top:<span class="string">"1cm"</span>, </span><br><span class="line"> bottom:<span class="string">"1cm"</span> </span><br><span class="line"> &#125; </span><br><span class="line"> </span><br><span class="line"> &#125;; </span><br><span class="line"> page.open(address, <span class="function"><span class="keyword">function</span>(<span class="params">status</span>) </span>&#123;</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'Status: '</span> + status);</span><br><span class="line"> <span class="keyword">if</span> (status !== <span class="string">'success'</span>) &#123;</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'Unable to load the address!'</span>);</span><br><span class="line"> phantom.exit(<span class="number">1</span>);</span><br><span class="line"> &#125; <span class="keyword">else</span> &#123;</span><br><span class="line"> <span class="keyword">var</span> bb = page.evaluate(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"> <span class="comment">//var child=document.getElementById("printBt");</span></span><br><span class="line"> <span class="comment">//child.parentNode.removeChild(child);//此外可以写一些对页面操作的代码,比如词句代码是删除页面上的打印按钮</span></span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">document</span>.getElementsByTagName(<span class="string">'html'</span>)[<span class="number">0</span>].getBoundingClientRect();<span class="comment">//返回内容就是要导出的范围(此处是HTML整页)</span></span><br><span class="line"> &#125;);</span><br><span class="line"> <span class="comment">// 截取范围</span></span><br><span class="line"> page.clipRect = &#123;</span><br><span class="line"> top : bb.top,</span><br><span class="line"> left : bb.left,</span><br><span class="line"> width : bb.width,</span><br><span class="line"> height : bb.height</span><br><span class="line"> &#125;;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">// 等待页面渲染</span></span><br><span class="line"> <span class="built_in">window</span>.setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"> page.render(output, &#123;<span class="attr">format</span>: <span class="string">'pdf'</span>, <span class="attr">quality</span>: <span class="string">'100'</span>&#125;);<span class="comment">//这里配置导出的格式pdf,png等,quality为导出质量</span></span><br><span class="line"> page.close();</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'渲染成功...'</span>);</span><br><span class="line"> phantom.exit();</span><br><span class="line"> &#125;, <span class="number">2000</span>);</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> &#125;);</span><br><span class="line">&#125;</span><br><span class="line">address = system.args[<span class="number">1</span>];<span class="comment">//传入的URL地址</span></span><br><span class="line">output = system.args[<span class="number">2</span>];<span class="comment">//保存的图片路径</span></span><br></pre></td></tr></table></figure>
<h4 id="2)测试命令"><a href="#2)测试命令" class="headerlink" title="2)测试命令"></a>2)测试命令</h4><p> 例如:phantomjs文件夹放于D盘根目录,在phantomjs/bin 目录下(也可以配置环境变量)打开控制台。以我的CSDN博客页面<code>https://blog.csdn.net/xiweiller</code>导出为PDF为例。输入如下命令:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">phantomjs.exe D:/phantomjs/html2pdf.js https://blog.csdn.net/xiweiller D:/phantomjs/blog.pdf</span><br></pre></td></tr></table></figure>
<p>其中 <code>phantomjs.exe</code>是执行命令文件, <code>D:/phantomjs/screenshot.js</code>是执行的配置js文件,<code>https://blog.csdn.net/xiweiller</code>是目标HTML,<code>D:/phantomjs/blog.pdf</code>是导出PDF的路径。</p>
<h4 id="3)-java中的使用,springboot项目为例"><a href="#3)-java中的使用,springboot项目为例" class="headerlink" title="3) java中的使用,springboot项目为例"></a>3) java中的使用,springboot项目为例</h4><ul>
<li><p>application.yml中添加配置,配置项为phantomjs执行文件路径</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">htmltopdf:</span></span><br><span class="line"><span class="attr"> path:</span></span><br><span class="line"><span class="attr"> windows:</span> <span class="attr">D:/phantomjs/bin/phantomjs.exe</span></span><br><span class="line"><span class="attr"> linux:</span> <span class="string">/root/soft/phantomjs-2.1.1-linux-x86_64/bin/phantomjs</span></span><br><span class="line"><span class="attr"> mac:</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Html转Pdf工具类</p>
<p>参数:</p>
<pre><code>- htmlPath 目标网页访问地址
- pdfPath 导出pdf存放目录
- JSESSIONID 登陆认证时需要传递,用于cookie携带
- domain cookie中获取
</code></pre></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Html转Pdf工具类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HtmlToPdf</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line"> <span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.windows&#125;"</span>)</span><br><span class="line"> <span class="keyword">private</span> String WINDOWS_WKHTMLTOPDF_PATH;</span><br><span class="line"> <span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.mac&#125;"</span>)</span><br><span class="line"> <span class="keyword">private</span> String MAC_WKHTMLTOPDF_PATH;</span><br><span class="line"> <span class="meta">@Value</span>(<span class="string">"$&#123;htmltopdf.path.linux&#125;"</span>)</span><br><span class="line"> <span class="keyword">private</span> String LINUX_WKHTMLTOPDF_PATH;</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">static</span> Logger log = LoggerFactory.getLogger(HtmlToPdf.class);</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * html转pdf核心方法</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> htmlPath html路径(硬盘和网盘路径都支持)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> pdfPath pdf存储路径</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> 转换成功:true,失败:false</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">convert</span><span class="params">(String htmlPath, String pdfPath,String JSESSIONID,String domain)</span> </span>&#123;</span><br><span class="line"> File file = <span class="keyword">new</span> File(pdfPath);</span><br><span class="line"> File parent = file.getParentFile();</span><br><span class="line"> <span class="keyword">if</span> (!parent.exists()) &#123;<span class="comment">// 如果pdf保存路径不存在,则创建路径</span></span><br><span class="line"> parent.mkdirs();</span><br><span class="line"> &#125;</span><br><span class="line"> String toolDir = <span class="keyword">null</span>;<span class="comment">// 转换工具在系统中的路径</span></span><br><span class="line"> <span class="keyword">if</span> (System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Windows"</span>) != -<span class="number">1</span>) &#123;<span class="comment">//windows 系统</span></span><br><span class="line"> toolDir = WINDOWS_WKHTMLTOPDF_PATH;</span><br><span class="line"> &#125;<span class="keyword">else</span> <span class="keyword">if</span>(System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Mac OS X"</span>) != -<span class="number">1</span>)&#123;<span class="comment">//mac 系统</span></span><br><span class="line"> toolDir = MAC_WKHTMLTOPDF_PATH;</span><br><span class="line"> &#125;<span class="keyword">else</span> <span class="keyword">if</span>(System.getProperty(<span class="string">"os.name"</span>).indexOf(<span class="string">"Linux"</span>) != -<span class="number">1</span>)&#123;<span class="comment">//linux 系统</span></span><br><span class="line"> toolDir = LINUX_WKHTMLTOPDF_PATH;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">boolean</span> result = <span class="keyword">true</span>;<span class="comment">//pdf创建成功标识,默认成功</span></span><br><span class="line"> String BLANK = <span class="string">" "</span>;<span class="comment">//空格</span></span><br><span class="line"> Process process = <span class="keyword">null</span>;<span class="comment">//图片输出路径</span></span><br><span class="line"> StringBuffer sbf = <span class="keyword">null</span>;</span><br><span class="line"> InputStream is = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line"> StringBuilder cmd = <span class="keyword">new</span> StringBuilder();</span><br><span class="line"> cmd.append(toolDir)</span><br><span class="line"> .append(BLANK)</span><br><span class="line"> .append(<span class="keyword">new</span> File(toolDir).getParent()).append(File.separator).append(<span class="string">"html2pdf.js"</span>)</span><br><span class="line"> .append(BLANK)</span><br><span class="line"> .append(htmlPath)</span><br><span class="line"> .append(BLANK)</span><br><span class="line"> .append(pdfPath);</span><br><span class="line"> <span class="keyword">if</span>(JSESSIONID!=<span class="keyword">null</span>)&#123;<span class="comment">//添加cookie值</span></span><br><span class="line"> cmd.append(BLANK).append(JSESSIONID);</span><br><span class="line"> cmd.append(BLANK).append(domain);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> log.info(<span class="string">"报表准备导出 "</span> );</span><br><span class="line"> log.info(<span class="string">"导出命令:&#123;&#125;"</span>,cmd.toString() );</span><br><span class="line"> process = Runtime.getRuntime().exec(cmd.toString());<span class="comment">// 输出路径</span></span><br><span class="line"></span><br><span class="line"> is = process.getInputStream();</span><br><span class="line"> BufferedReader br = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(is));</span><br><span class="line"> sbf = <span class="keyword">new</span> StringBuffer();</span><br><span class="line"> String tmp = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">while</span> ((tmp = br.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line"> sbf.append(tmp);</span><br><span class="line"> &#125;</span><br><span class="line"> log.info(<span class="string">"报表导出完成 "</span> );</span><br><span class="line"> &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line"> result = <span class="keyword">false</span>;</span><br><span class="line"> log.error(<span class="string">"报表导出失败!"</span>, e);</span><br><span class="line"> &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line"> <span class="keyword">if</span> (is != <span class="keyword">null</span>) &#123;</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> is.close();</span><br><span class="line"> &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> &#125;</span><br><span class="line"> is = <span class="keyword">null</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p>转换工具的调用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">( HttpServletRequest request )</span></span>&#123;</span><br><span class="line"> <span class="comment">// 注意不同部署环境,路径不同。</span></span><br><span class="line"> String htmlUrl = <span class="string">"D:/phantomjs/html2pdf.js"</span>;</span><br><span class="line"> String pdfPath = <span class="string">"D:/phantomjs/export.pdf"</span></span><br><span class="line"> String JSESSIONID = <span class="string">""</span>;</span><br><span class="line"> String domain = request.getServerName();</span><br><span class="line"> Cookie[] cookies = request.getCookies();</span><br><span class="line"> <span class="keyword">for</span>(Cookie cookie :cookies)&#123;</span><br><span class="line"> <span class="keyword">if</span>(<span class="string">"JSESSIONID"</span>.equals(cookie.getName()))&#123;</span><br><span class="line"> JSESSIONID = cookie.getValue();</span><br><span class="line"> &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="comment">//将html转换为pdf文件</span></span><br><span class="line"> <span class="keyword">boolean</span> isno =htmlToPdf.convert(htmlUrl,pdfPath,JSESSIONID,domain);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-导出效果图"><a href="#4-导出效果图" class="headerlink" title="4) 导出效果图"></a>4) 导出效果图</h4><p><img src="https://img-blog.csdnimg.cn/20190912142654887.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpd2VpbGxlcg==,size_16,color_FFFFFF,t_70" alt="页面导出效果"></p>
<h3 id="4-注意事项"><a href="#4-注意事项" class="headerlink" title="4. 注意事项"></a>4. 注意事项</h3><p>​ 在实际项目使用时,我们必须保证页面异步加载的速度比较快,否则会出现页面渲染不完整的问题。因此在项目中,被导出的目标页面最好能做到快速响应,尽量减少异步请求加载,或者保证异步接口快速响应。</p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/09/01/2019-09-01-简单的HTML快照生成,导出pdf或图片/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/09/01/2019-09-01-简单的HTML快照生成,导出pdf或图片/" itemprop="url">简单的HTML快照生成,导出pdf或图片</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-01T10:00:00+08:00">
2019-09-01
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/javascript/" itemprop="url" rel="index">
<span itemprop="name">javascript</span>
</a>
</span>
</span>
<span id="/2019/09/01/2019-09-01-简单的HTML快照生成,导出pdf或图片/" class="leancloud_visitors" data-flag-title="简单的HTML快照生成,导出pdf或图片">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<h3 id="一、利用-html2canvas实现HTML页面截图"><a href="#一、利用-html2canvas实现HTML页面截图" class="headerlink" title="一、利用 html2canvas实现HTML页面截图"></a>一、利用 html2canvas实现HTML页面截图</h3><blockquote>
<p>官方网址:<a href="https://html2canvas.hertzen.com/" target="_blank" rel="noopener"> https://html2canvas.hertzen.com/ </a></p>
<p>GitHub:<a href="https://github.com/niklasvh/html2canvas" target="_blank" rel="noopener">https://github.com/niklasvh/html2canvas</a></p>
</blockquote>
<h4 id="1-HTML页面引入-html2canvas-min-js"><a href="#1-HTML页面引入-html2canvas-min-js" class="headerlink" title="1.HTML页面引入 html2canvas.min.js"></a>1.HTML页面引入 <code>html2canvas.min.js</code></h4><h4 id="2-定义一个截图的触发按钮"><a href="#2-定义一个截图的触发按钮" class="headerlink" title="2.定义一个截图的触发按钮"></a>2.定义一个截图的触发按钮</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"exprotImg();"</span>&gt;</span>导出图片<span class="tag">&lt;/<span class="name">button</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">""</span> <span class="attr">download</span>=<span class="string">"canvas.png"</span> <span class="attr">id</span>=<span class="string">"save_href"</span> <span class="attr">style</span>=<span class="string">"display:none"</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">""</span> <span class="attr">id</span>=<span class="string">"save_img"</span>/&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="3-js代码"><a href="#3-js代码" class="headerlink" title="3.js代码"></a>3.js代码</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">exprotImg</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"> <span class="comment">// 要截图的元素</span></span><br><span class="line"> <span class="keyword">var</span> element = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'html'</span>)[<span class="number">0</span>];</span><br><span class="line"> <span class="comment">// 获取元素的大小及其相对于视口的位置等参数</span></span><br><span class="line"> <span class="keyword">var</span> dd= element.getBoundingClientRect();</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> opts = &#123;</span><br><span class="line"> scale: <span class="number">2</span>, <span class="comment">// 添加的scale 参数</span></span><br><span class="line"> <span class="comment">// logging: true, //日志开关,便于查看html2canvas的内部执行流程</span></span><br><span class="line"> width: dd.width, <span class="comment">//dom 原始宽度</span></span><br><span class="line"> height: dd.height,</span><br><span class="line"> useCORS: <span class="literal">true</span>, <span class="comment">// 【重要】开启跨域配置</span></span><br><span class="line"> allowTaint:<span class="literal">true</span></span><br><span class="line"> &#125;;</span><br><span class="line"></span><br><span class="line"> html2canvas(element,opts).then(<span class="function"><span class="keyword">function</span>(<span class="params">canvas</span>) </span>&#123;</span><br><span class="line"> <span class="comment">// 模拟的下载按钮</span></span><br><span class="line"> <span class="keyword">var</span> svaeHref = <span class="built_in">document</span>.getElementById(<span class="string">"save_href"</span>);</span><br><span class="line"> <span class="keyword">var</span> img = <span class="built_in">document</span>.getElementById(<span class="string">"save_img"</span>);</span><br><span class="line"> <span class="keyword">var</span> tempSrc = canvas.toDataURL(<span class="string">"image/png"</span>);</span><br><span class="line"> svaeHref.href=tempSrc;</span><br><span class="line"> img.src=tempSrc;</span><br><span class="line"> $(img).click();</span><br><span class="line"> &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="二、利用-html2pdf-实现页面导出pdf"><a href="#二、利用-html2pdf-实现页面导出pdf" class="headerlink" title="二、利用 html2pdf 实现页面导出pdf"></a>二、利用 html2pdf 实现页面导出pdf</h3><blockquote>
<p>GitHub :<a href="https://github.com/eKoopmans/html2pdf" target="_blank" rel="noopener">https://github.com/eKoopmans/html2pdf</a> </p>
</blockquote>
<h4 id="1-页面导入-html2pdf-bundle-min-js"><a href="#1-页面导入-html2pdf-bundle-min-js" class="headerlink" title="1.页面导入 html2pdf.bundle.min.js"></a>1.页面导入 <code>html2pdf.bundle.min.js</code></h4><h4 id="2-导出按钮"><a href="#2-导出按钮" class="headerlink" title="2.导出按钮"></a>2.导出按钮</h4><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">"exprotPdf();"</span>&gt;</span>导出pdf<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="3-js代码-1"><a href="#3-js代码-1" class="headerlink" title="3.js代码"></a>3.js代码</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">exprotPdf</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"> <span class="comment">// 要截图的元素</span></span><br><span class="line"> <span class="keyword">var</span> element = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'html'</span>)[<span class="number">0</span>];</span><br><span class="line"> <span class="comment">// 获取元素的大小及其相对于视口的位置等参数</span></span><br><span class="line"> <span class="keyword">var</span> opt = &#123;</span><br><span class="line"> margin: <span class="number">1</span>,</span><br><span class="line"> filename: <span class="string">'myfile.pdf'</span>,</span><br><span class="line"> image: &#123; <span class="attr">type</span>: <span class="string">'png'</span>, <span class="attr">quality</span>: <span class="number">0.98</span> &#125;,</span><br><span class="line"> html2canvas: &#123;</span><br><span class="line"> scale: <span class="number">2</span>,</span><br><span class="line"> useCORS:<span class="literal">true</span>, <span class="comment">// 【重要】开启跨域配置</span></span><br><span class="line"> allowTaint:<span class="literal">true</span>,</span><br><span class="line"> width:dd.width,</span><br><span class="line"> height:dd.height</span><br><span class="line"> &#125;,</span><br><span class="line"> jsPDF: &#123; <span class="attr">unit</span>: <span class="string">'in'</span>, <span class="attr">format</span>: <span class="string">'letter'</span>, <span class="attr">orientation</span>: <span class="string">'portrait'</span> &#125;</span><br><span class="line"> &#125;;</span><br><span class="line"></span><br><span class="line"> html2pdf().from(element).set(opt).save();</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/08/15/2019-08-15-利用自定义注解,统计方法执行时间/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/08/15/2019-08-15-利用自定义注解,统计方法执行时间/" itemprop="url">利用自定义注解,统计方法执行时间</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-08-15T15:00:00+08:00">
2019-08-15
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/java/" itemprop="url" rel="index">
<span itemprop="name">java</span>
</a>
</span>
</span>
<span id="/2019/08/15/2019-08-15-利用自定义注解,统计方法执行时间/" class="leancloud_visitors" data-flag-title="利用自定义注解,统计方法执行时间">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<blockquote>
<p>项目中需要统计某些方法的执行时间,最简易的方式是方法执行前记录时间戳startTime,在方法结束前,用时间戳endTime-startTime得出该方法耗时。<br>但是为了避免无代码侵入并实现通用,于是定义一个注解,如果要统计哪个方法,只需在方法上写上注解即可,通过注解可以获取到方法的参数、方法名、返回值等等信息。</p>
</blockquote>
<p>下面是一个简单的时间统计实现:</p>
<h3 id="1-定义一个注解TimeConsume"><a href="#1-定义一个注解TimeConsume" class="headerlink" title="1.定义一个注解TimeConsume"></a>1.定义一个注解<code>TimeConsume</code></h3><p>该注解有一个默认的value属性,value值为方法名或自定义的描述<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> TimeConsume &#123;</span><br><span class="line"></span><br><span class="line"> <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> "方法"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="2-使用Aspect定义该注解的切面TimeConsumeAspect"><a href="#2-使用Aspect定义该注解的切面TimeConsumeAspect" class="headerlink" title="2.使用Aspect定义该注解的切面TimeConsumeAspect"></a>2.使用Aspect定义该注解的切面<code>TimeConsumeAspect</code></h3><p>定义好注解后,需要对该注解使用的类进行监听,利用Spring框架Aspect实现切面,定义环绕通知,获取到方法的参数、方法名等信息,便于统计所需。对执行方法进行异常捕获,在<code>finally</code>代码块中实现时间统计逻辑,避免方法异常无法统计。代码如下:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TimeConsumeAspect</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 切点定义为注解<span class="doctag">@annotation</span>(注解类路径)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="meta">@Pointcut</span>(<span class="string">"@annotation(com.weiller.demo.common.annotation.TimeConsume)"</span>)</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">consume</span><span class="params">()</span></span>&#123;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@Around</span>(<span class="string">"consume()"</span>)</span><br><span class="line"> <span class="keyword">public</span> &lt;T&gt; <span class="function">T <span class="title">around</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line"> Long startTime = System.currentTimeMillis();</span><br><span class="line"> </span><br><span class="line"> Object[] args = pjp.getArgs();</span><br><span class="line"> T result;</span><br><span class="line"> Method methodClass;</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"></span><br><span class="line"> result = (T)pjp.proceed(args);<span class="comment">//执行方法</span></span><br><span class="line"></span><br><span class="line"> &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line"> <span class="keyword">long</span> endTime = System.currentTimeMillis();</span><br><span class="line"> Signature signature = pjp.getSignature();</span><br><span class="line"> String methodName = signature.getName();</span><br><span class="line"> Class&lt;?&gt; targetClass = pjp.getTarget().getClass();</span><br><span class="line"> Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes();</span><br><span class="line"> methodClass = targetClass.getMethod(methodName, parameterTypes);</span><br><span class="line"> Annotation[] annotations = methodClass.getAnnotations();</span><br><span class="line"> <span class="keyword">for</span> (Annotation annotation : annotations)&#123;</span><br><span class="line"> Class&lt;? extends Annotation&gt; aClass = annotation.annotationType();</span><br><span class="line"> String simpleName = aClass.getSimpleName();</span><br><span class="line"> <span class="keyword">if</span>(<span class="string">"TimeConsume"</span>.equals(simpleName))&#123;</span><br><span class="line"> TimeConsume timeConsume = (TimeConsume) annotation;</span><br><span class="line"> String value = timeConsume.value();</span><br><span class="line"> log.info(value+<span class="string">"[&#123;&#125;] 执行耗时:&#123;&#125;ms"</span>,methodName,endTime-startTime);</span><br><span class="line"> <span class="keyword">break</span>;</span><br><span class="line"> &#125;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> result;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="3-测试目标方法中使用"><a href="#3-测试目标方法中使用" class="headerlink" title="3.测试目标方法中使用"></a>3.测试目标方法中使用</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/test"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">testController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"> <span class="meta">@TimeConsume</span>(<span class="string">"测试"</span>)</span><br><span class="line"> <span class="meta">@GetMapping</span>(<span class="string">"info"</span>)</span><br><span class="line"> <span class="function"><span class="keyword">public</span> Object <span class="title">testInfo</span><span class="params">()</span></span>&#123;</span><br><span class="line"> Object parse = JSONObject.parse(<span class="string">"&#123;\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"requestId\":\"\",\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"appId\":\"\",\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"nonce\":\"\",\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"timestamp\":12345676543,\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"signature\":\"\",\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"sjgsd\":\"61000\",\n"</span> +</span><br><span class="line"> <span class="string">"\t\t\"starTime\":12345676543\n"</span> +</span><br><span class="line"> <span class="string">"\t&#125;"</span>);</span><br><span class="line"> <span class="keyword">try</span> &#123;</span><br><span class="line"> Thread.sleep(<span class="keyword">new</span> Random().nextInt(<span class="number">100</span>));<span class="comment">//随机时间休眠</span></span><br><span class="line"> &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line"> e.printStackTrace();</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">return</span> parse ;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
<article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
<div class="post-block">
<link itemprop="mainEntityOfPage" href="http://weiller.com/2019/07/19/2019-07-19-sql-editor/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="惠维乐">
<meta itemprop="description" content>
<meta itemprop="image" content="/images/avatar.jpg">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="WeillerBlog">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
<a class="post-title-link" href="/2019/07/19/2019-07-19-sql-editor/" itemprop="url">在线sql编辑查询工具sql-editor</a></h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-19T11:13:00+08:00">
2019-07-19
</time>
</span>
<span class="post-category">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/前端/" itemprop="url" rel="index">
<span itemprop="name">前端</span>
</a>
</span>
</span>
<span id="/2019/07/19/2019-07-19-sql-editor/" class="leancloud_visitors" data-flag-title="在线sql编辑查询工具sql-editor">
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读次数&#58;</span>
<span class="leancloud-visitors-count"></span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<blockquote>
<p>sql-editor是基于CodeMirror的一个在线sql编辑工具,模仿navicat工具,开发的一个简易版。</p>
</blockquote>
<pre><code>目前只提供前端代码,由easy-mock提供json测试数据。
</code></pre><blockquote>
<p>Github地址: <code>https://github.com/xiweile/sql-editor</code></p>
</blockquote>
<h3 id="功能更新"><a href="#功能更新" class="headerlink" title="功能更新"></a>功能更新</h3><ul>
<li>左侧提供数据库表字段树形结构,可拖拽到sql编辑框。(2019-7-19新增)</li>
<li>编辑区和数据展示区上下拖动更改大小。(2019-7-19新增)</li>
<li>执行与中断功能。(2019-7-19新增)</li>
<li>自定义外部接口获取sql关键词、函数、表字段等,用于sql编辑时提示补全,键盘录入后自动提示,上下键选择,tab键或点击选中项自动补全。(2019-7-16)</li>
<li>sql格式化。(2019-7-16)</li>
</ul>
<h3 id="一些截图:"><a href="#一些截图:" class="headerlink" title="一些截图:"></a>一些截图:</h3><p><img src="../images/sql-editor/pic_01.png" alt="image"></p>
<p><img src="../images/sql-editor/pic_02.png" alt="img"></p>
<p><img src="../images/sql-editor/pic_03.png" alt="img"></p>
</div>
<footer class="post-footer">
<div class="post-eof"></div>
</footer>
</div>
</article>
</section>
<nav class="pagination">
<span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><a class="extend next" rel="next" href="/page/2/"><i class="fa fa-angle-right"></i></a>
</nav>
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview-wrap sidebar-panel sidebar-panel-active">
<div class="site-overview">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="惠维乐">
<p class="site-author-name" itemprop="name">惠维乐</p>
<p class="site-description motion-element" itemprop="description">IT技术文章/JAVA学习分享/个人随笔</p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives/">
<span class="site-state-item-count">12</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<a href="/categories/index.html">
<span class="site-state-item-count">5</span>
<span class="site-state-item-name">分类</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
<span class="links-of-author-item">
<a href="https://github.com/xiweile" target="_blank" title="GitHub">
<i class="fa fa-fw fa-github"></i>GitHub</a>
</span>
<span class="links-of-author-item">
<a href="https://blog.csdn.net/xiweiller" target="_blank" title="CSDN">
<i class="fa fa-fw fa-copyright"></i>CSDN</a>
</span>
<span class="links-of-author-item">
<a href="mailto:weiller@126.com" target="_blank" title="E-Mail">
<i class="fa fa-fw fa-envelope"></i>E-Mail</a>
</span>
</div>
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
<span class="with-love">
<i class="fa fa-user"></i>
</span>
<span class="author" itemprop="copyrightHolder">惠维乐</span>
</div>
<div class="busuanzi-count">
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv">
<i class="fa fa-users"></i> 本站访客数
<span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
人次
</span>
<span class="site-pv">
<i class="fa fa-eye"></i> 总访问量
<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
</span>
</div>
<div>
<script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1276853944'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s5.cnzz.com/z_stat.php%3Fid%3D1276853944%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>
<script type="text/javascript">
// Popup Window;
var isfetched = false;
var isXml = true;
// Search DB path;
var search_path = "search.xml";
if (search_path.length === 0) {
search_path = "search.xml";
} else if (/json$/i.test(search_path)) {
isXml = false;
}
var path = "/" + search_path;
// monitor main search box;
var onPopupClose = function (e) {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
}
function proceedsearch() {
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr("autocapitalize", "none");
$localSearchInput.attr("autocorrect", "off");
$localSearchInput.focus();
}
// search function;
var searchFunc = function(path, search_id, content_id) {
'use strict';
// start loading animation
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay">' +
'<div id="search-loading-icon">' +
'<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
'</div>' +
'</div>')
.css('overflow', 'hidden');
$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');
$.ajax({
url: path,
dataType: isXml ? "xml" : "json",
async: true,
success: function(res) {
// get the contents from search data
isfetched = true;
$('.popup').detach().appendTo('.header-inner');
var datas = isXml ? $("entry", res).map(function() {
return {
title: $("title", this).text(),
content: $("content",this).text(),
url: $("url" , this).text()
};
}).get() : res;
var input = document.getElementById(search_id);
var resultContent = document.getElementById(content_id);
var inputEventFunction = function() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[\s\-]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// perform local searching
datas.forEach(function(data) {
var isMatch = false;
var hitCount = 0;
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content.trim().replace(/<[^>]+>/g,"");
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url);
var indexOfTitle = [];
var indexOfContent = [];
// only match articles with not empty titles
if(title != '') {
keywords.forEach(function(keyword) {
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({position: position, word: word});
startPosition = position + wordLen;
}
return index;
}
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
isMatch = true;
hitCount = indexOfTitle.length + indexOfContent.length;
}
}
// show search results
if (isMatch) {
// sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function (index) {
index.sort(function (itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
// merge hits into slices
function mergeIntoSlice(text, start, end, index) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length != 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({position: position, length: word.length});
var wordEnd = position + word.length;
// move to next position of hit
index.pop();
while (index.length != 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
searchTextCount += searchTextCountInSlice;
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
var slicesOfTitle = [];
if (indexOfTitle.length != 0) {
slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
}
var slicesOfContent = [];
while (indexOfContent.length != 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// cut out 100 characters
var start = position - 20;
var end = position + 80;
if(start < 0){
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if(end > content.length){
end = content.length;
}
slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
}
// sort slices in content by search text's count and hits' count
slicesOfContent.sort(function (sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// select top N slices in content
var upperBound = parseInt('1');
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
// highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function (hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
var resultItem = '';
if (slicesOfTitle.length != 0) {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
} else {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
}
slicesOfContent.forEach(function (slice) {
resultItem += "<a href='" + articleUrl + "'>" +
"<p class=\"search-result\">" + highlightKeyword(content, slice) +
"...</p>" + "</a>";
});
resultItem += "</li>";
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
})
};
if (keywords.length === 1 && keywords[0] === "") {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
} else {
resultItems.sort(function (resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class=\"search-result-list\">';
resultItems.forEach(function (result) {
searchResultList += result.item;
})
searchResultList += "</ul>";
resultContent.innerHTML = searchResultList;
}
}
if ('auto' === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// remove loading animation
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
proceedsearch();
}
});
}
// handle and trigger popup window;
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc(path, 'local-search-input', 'local-search-result');
} else {
proceedsearch();
};
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e){
e.stopPropagation();
});
$(document).on('keyup', function (event) {
var shouldDismissSearchPopup = event.which === 27 &&
$('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});
</script>
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
<script>AV.initialize("e7h0BlhhzchHRhKnkOXA3Xiy-gzGzoHsz", "RfdAeLEHuGFEEFwJleHOnszU");</script>
<script>
function showTime(Counter) {
var query = new AV.Query(Counter);
var entries = [];
var $visitors = $(".leancloud_visitors");
$visitors.each(function () {
entries.push( $(this).attr("id").trim() );
});
query.containedIn('url', entries);
query.find()
.done(function (results) {
var COUNT_CONTAINER_REF = '.leancloud-visitors-count';
if (results.length === 0) {
$visitors.find(COUNT_CONTAINER_REF).text(0);
return;
}
for (var i = 0; i < results.length; i++) {
var item = results[i];
var url = item.get('url');
var time = item.get('time');
var element = document.getElementById(url);
$(element).find(COUNT_CONTAINER_REF).text(time);
}
for(var i = 0; i < entries.length; i++) {
var url = entries[i];
var element = document.getElementById(url);
var countSpan = $(element).find(COUNT_CONTAINER_REF);
if( countSpan.text() == '') {
countSpan.text(0);
}
}
})
.fail(function (object, error) {
console.log("Error: " + error.code + " " + error.message);
});
}
function addCount(Counter) {
var $visitors = $(".leancloud_visitors");
var url = $visitors.attr('id').trim();
var title = $visitors.attr('data-flag-title').trim();
var query = new AV.Query(Counter);
query.equalTo("url", url);
query.find({
success: function(results) {
if (results.length > 0) {
var counter = results[0];
counter.fetchWhenSave(true);
counter.increment("time");
counter.save(null, {
success: function(counter) {
var $element = $(document.getElementById(url));
$element.find('.leancloud-visitors-count').text(counter.get('time'));
},
error: function(counter, error) {
console.log('Failed to save Visitor num, with error message: ' + error.message);
}
});
} else {
var newcounter = new Counter();
/* Set ACL */
var acl = new AV.ACL();
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
newcounter.setACL(acl);
/* End Set ACL */
newcounter.set("title", title);
newcounter.set("url", url);
newcounter.set("time", 1);
newcounter.save(null, {
success: function(newcounter) {
var $element = $(document.getElementById(url));
$element.find('.leancloud-visitors-count').text(newcounter.get('time'));
},
error: function(newcounter, error) {
console.log('Failed to create');
}
});
}
},
error: function(error) {
console.log('Error:' + error.code + " " + error.message);
}
});
}
$(function() {
var Counter = AV.Object.extend("Counter");
if ($('.leancloud_visitors').length == 1) {
addCount(Counter);
} else if ($('.post-title-link').length > 1) {
showTime(Counter);
}
});
</script>
</body>
</html>
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
HTML
1
https://gitee.com/xiweile/xiweile.github.io.git
git@gitee.com:xiweile/xiweile.github.io.git
xiweile
xiweile.github.io
xiweile.github.io
master

搜索帮助