├── README.md ├── front ├── index.html ├── index.tpl.html ├── package.json ├── postcss.config.js └── src │ ├── App.vue │ ├── components │ ├── DbFilterinput.vue │ ├── DbFooter.vue │ ├── DbHeader.vue │ ├── DbModal.vue │ ├── DbSidebar.vue │ └── DbTable.vue │ ├── eventBus.js │ └── main.js ├── gzip.conf ├── nginx.conf ├── pic.png ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── demo │ │ ├── Application.java │ │ ├── bean │ │ ├── PageNumber.java │ │ ├── Persons.java │ │ ├── Progress.java │ │ ├── SelectCondition.java │ │ ├── Student.java │ │ ├── TreeNode.java │ │ └── User.java │ │ ├── commandline │ │ ├── InitTreeNode.java │ │ └── TestConcurrentHashMap.java │ │ ├── component │ │ ├── CustomMultipartResolver.java │ │ ├── FileUploadProgressListener.java │ │ ├── SpringContext.java │ │ └── WebmvcConfig.java │ │ ├── controller │ │ ├── BaseController.java │ │ ├── FileUploadController.java │ │ ├── MainController.java │ │ ├── SelectionConditionController.java │ │ ├── StudentController.java │ │ ├── TestVuex.java │ │ ├── TreeNodeController.java │ │ └── UserController.java │ │ ├── filter │ │ └── FilterDemo.java │ │ ├── interceptor │ │ └── InterceptorDemo.java │ │ ├── jfreechart │ │ ├── Barchart.java │ │ ├── ChartServlet.java │ │ ├── CreateJFreeChart.java │ │ ├── CustomLegendTitle.java │ │ ├── JFreeChartDemo.java │ │ ├── JFreeChartDemoCombined.java │ │ ├── JFreeChartDemoCombined2.java │ │ ├── LayeredBarChartDemo.java │ │ ├── LineChart.java │ │ ├── Piechart.java │ │ ├── TestTimeSeriesChart.java │ │ └── TimeSeriesChart.java │ │ ├── lambda │ │ ├── LambdaTest.java │ │ └── TestMap.java │ │ ├── listener │ │ ├── RequestListenerDemo.java │ │ ├── ServletContextListenerDemo.java │ │ └── SessionListenerDemo.java │ │ ├── pagination │ │ ├── PaginationFormatting.java │ │ └── PaginationMultiTypeValuesHelper.java │ │ ├── repository │ │ ├── PersonsRepository.java │ │ ├── StudentRepository.java │ │ ├── TreeNodeRepository.java │ │ └── UserRepository.java │ │ └── utils │ │ ├── FileUploadUtil.java │ │ ├── HanyuPinyinHelper.java │ │ └── SpringUtil.java └── resources │ ├── application.properties │ └── static │ ├── canvs.js │ ├── chart-backup.html │ ├── chart.html │ ├── chart.js │ ├── data.json │ ├── force.html │ └── jquery-3.2.1.min.js └── test └── java └── com └── example └── demo └── ApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | ### 感谢 2 | 感谢作者:Boyle 3 | from:https://github.com/boylegu/SpringBoot-vue 4 | 大部分都是来自于Boyle的项目 5 | 6 | 感谢作者:janessssss 7 | https://github.com/janessssss/vuejs-element 8 | 借用了user curd 的demo 9 | 10 | 感谢作者:lin-xin 11 | https://github.com/lin-xin/vue-manage-system 12 | 13 | ### 目的 14 | 练习spring-boot 整合vue 15 | 16 | 17 | ### 运行 18 | 启动boot项目在8000端口 19 | 20 | 在cmd命令行到front目录先安装vue环境(npm install,当然前提是 安装了nodejs) 21 | 然后运行front,在命令行中:npm dev run 22 | 23 | 24 | boyle 的github 也有介绍请参考:https://github.com/boylegu/SpringBoot-vue 25 | 26 | 27 | ### 需要注意的地方 28 | 踩坑1:PageNumber:对jpa查询后的number进行了修正(默认是0 ,而前端页面需要的是1) 29 | 采坑2:在User类中,如果创建时间使用create_time,下划线的方式连接变量,那采用jpa根据字段排序的时候是无法区分的, 30 | 改用驼峰式的命名就好啦 31 | 32 | 33 | 和这个项目配套的前段项目可以是本项目的front 34 | 也可以是:https://github.com/ninuxGithub/vue-front-end 35 | 36 | ### jpa分页 37 | 重点:分页对象的repository要继承JpaSpecificationExecutor 38 | ```java 39 | public Page queryPagination(Integer page, Integer perPage, String sortType, Map params, 40 | Class beanClass) { 41 | if (page == null) { 42 | page = 1; 43 | } 44 | Sort sort = null; 45 | Direction direction = Direction.ASC; 46 | if (StringUtils.isBlank(sortType)) { 47 | sort = new Sort(direction, "id"); 48 | } else { 49 | if (sortType.startsWith("-")) { 50 | direction = Direction.DESC; 51 | sortType = sortType.substring(1); 52 | } 53 | sort = new Sort(direction, sortType); 54 | } 55 | // 创建pageable对象 56 | Pageable pageable = new PageRequest(page - 1, perPage == null ? maxPerPage : perPage, sort); 57 | // 开始获取分页的JpaSpecificationExecutor 58 | JpaSpecificationExecutor bean = (JpaSpecificationExecutor) springUtil.getBean(beanClass); 59 | logger.info("sort field :{} queryPagination run...", sortType); 60 | // 开始分页 61 | Page pagination = bean.findAll(new Specification() { 62 | @Override 63 | public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { 64 | List predicatList = new ArrayList<>(); 65 | for (String field : params.keySet()) { 66 | Object value = params.get(field); 67 | if (null != value && StringUtils.isNotBlank(value.toString())) { 68 | //有些字段是不可以采用like的 例如Double ... 69 | predicatList.add(cb.like(root.get(field), "%" + value + "%")); 70 | } 71 | } 72 | Predicate[] arrayPredicates = new Predicate[predicatList.size()]; 73 | return cb.and(predicatList.toArray(arrayPredicates)); 74 | } 75 | }, pageable); 76 | // 对分页的PageNumber 进行调整 77 | return new PageNumber<>(pagination.getContent(), pageable, pagination.getTotalElements()); 78 | } 79 | ``` 80 | 81 | ### element-ui fileupload 82 | 文件上组件的使用,以及spring-boot 后台对文件上传的处理 83 | 84 | ### vue 组件的变量传递,组件的通信 85 | 可以参考StudentTable.vue ,SearchStudent.vue, 重点在 86 | 'keywords': 'filterResultData' 87 | 收到vue的监控,如果搜索的变量发送了改变,那么就会触发filterResultData,进行搜索返回分页的结果 88 | 再通过Even发送给StudentTable.vue组件,实现了变量的传递,从而实现了组件的通信 89 | 90 | 91 | ### filter,interceptor,listener 注解实现的方式 92 | filter: 93 | 采用注解@Order(value = Ordered.HIGHEST_PRECEDENCE)@WebFilter(urlPatterns = "/*", filterName = "apiFilter") , 实现接口javax.servlet.Filter 94 | 95 | interceptor: 96 | 需要实现接口:org.springframework.web.servlet.HandlerInterceptor,并且在webmvconfig 中的addInterceptors方法中注入拦截器 97 | 98 | listener: 99 | javax.servlet.http.HttpSessionListener--session级别(经过采坑,requestMapping 方法需要有HttpSession的入参,才会得到监听) 100 | javax.servlet.ServletContextListener--servlet容器配置 101 | javax.servlet.ServletRequestListener--request级别的监听 102 | 另外还有一个重要的点就是需要在applicaton中加入注解@ServletComponentScan,扫描组件 103 | 104 | ### axois 发送post get 105 | ```javascript 106 | //get 107 | axios.get(this.url,{params:this.filter}).then((response) =>{ 108 | this.students = response.data.content; 109 | }).catch((response)=>{ 110 | this.$message.error('message'); 111 | }); 112 | 113 | //axios post 需要借助qs 将参数sringify 114 | var qs = require('qs'); 115 | axios.post('/api/changeColor',qs.stringify({'color':color})).then(function(response) { 116 | 117 | }).catch(function(error) { 118 | 119 | }); 120 | 121 | ``` 122 | 123 | ### 效果 124 | ![img](https://github.com/ninuxGithub/spring-boot-vue-separate/blob/master/pic.png) 125 | 126 | 127 | 128 | ##Nginx 配置文件 129 | 130 | #Nginx所用用户和组,window下不指定 131 | #user niumd niumd; 132 | #工作的子进程数量(通常等于CPU数量或者2倍于CPU) 133 | worker_processes 2; 134 | #错误日志存放路径 135 | #error_log logs/error.log; 136 | #error_log logs/error.log notice; 137 | error_log logs/error.log info; 138 | #指定pid存放文件 139 | pid logs/nginx.pid; 140 | events { 141 | #使用网络IO模型linux建议epoll,FreeBSD建议采用kqueue,window下不指定。 142 | #use epoll; 143 | #允许最大连接数 144 | worker_connections 1024; 145 | } 146 | http { 147 | include mime.types; 148 | default_type application/octet-stream; 149 | #定义日志格式 150 | #log_format main '$remote_addr - $remote_user [$time_local] $request ' 151 | #'"$status" $body_bytes_sent "$http_referer" ' 152 | #'"$http_user_agent" "$http_x_forwarded_for"'; 153 | #access_log off; 154 | access_log logs/access.log; 155 | client_header_timeout 3m; 156 | client_body_timeout 3m; 157 | send_timeout 3m; 158 | client_header_buffer_size 1k; 159 | large_client_header_buffers 4 4k; 160 | sendfile on; 161 | tcp_nopush on; 162 | tcp_nodelay on; 163 | #keepalive_timeout 75 20; 164 | include gzip.conf; 165 | upstream backend_server { 166 | #根据ip计算将请求分配各那个后端tomcat,许多人误认为可以解决session问题,其实并不能。 167 | #同一机器在多网情况下,路由切换,ip可能不同 168 | #ip_hash; 169 | server localhost:8000 weight=5; 170 | server localhost:9000 weight=5; 171 | } 172 | 173 | #访问nginx自带的页面nginx首页地址:http://www.nginxserver.com:8080/ 174 | server { 175 | listen 8080; 176 | server_name www.nginxserver.com; 177 | index index.html index.htm; 178 | root html; 179 | location /{ 180 | 181 | } 182 | } 183 | 184 | #通过代理访问后台的服务器:http://www.nginxserver.com/ 185 | server { 186 | listen 80; 187 | server_name www.nginxserver.com; 188 | #index index.html index.htm; 189 | #root html; 190 | 191 | location / { 192 | #proxy_connect_timeout 3; 193 | #proxy_send_timeout 30; 194 | #proxy_read_timeout 30; 195 | 196 | proxy_pass http://backend_server; 197 | 198 | #proxy config 199 | proxy_redirect off; 200 | proxy_set_header Host $host:$server_port; 201 | proxy_set_header X-Real-IP $remote_addr; 202 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 203 | client_max_body_size 10m; 204 | client_body_buffer_size 128k; 205 | proxy_connect_timeout 300; 206 | proxy_send_timeout 300; 207 | proxy_read_timeout 300; 208 | proxy_buffer_size 4k; 209 | proxy_buffers 4 32k; 210 | proxy_busy_buffers_size 64k; 211 | proxy_temp_file_write_size 64k; 212 | } 213 | } 214 | } 215 | 216 | 217 | 218 | server_name www.nginxserver.com 需要配置到host里面 219 | 220 | [参考] 221 | nginx反向代理配置keepalive 222 | keepalive for HTTP - Module ngx_http_core_module 223 | 224 | 2. Tomcat 225 | conf/server.xml: 226 | 242 | 257 | [参考] 258 | The HTTP Connector - Tomcat 7 Configuration Reference 259 | 260 | 3. Client 261 | 客户端HTTP "Keep-Alive"实现代码,请打开下一行的链接。 262 | KeepAliveHttpClientsTest -> httpclient-x 263 | 264 | 【结果验证】 265 | 使用 "sudo netstat -antp | grep 80" 监控与Nginx相关的线程状态 266 | 267 | 268 | ## select , poll , epoll 的区别 269 | [博客链接](https://www.cnblogs.com/Anker/p/3265058.html) 270 | 271 | 272 | -------------------------------------------------------------------------------- /front/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /front/index.tpl.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /front/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webpack2", 3 | "version": "1.0.0", 4 | "description": "", 5 | "dependencies": { 6 | "vue-resource": "^1.3.4", 7 | "vue-router": "^3.0.1", 8 | "webpack": "^2.4.1" 9 | }, 10 | "devDependencies": { 11 | "apidoc": "^0.17.6", 12 | "autoprefixer": "^7.0.1", 13 | "axios": "^0.16.2", 14 | "babel-core": "^6.24.1", 15 | "babel-loader": "^6.4.1", 16 | "babel-plugin-component": "^0.9.1", 17 | "babel-preset-es2015": "^6.24.1", 18 | "css-loader": "^0.28.4", 19 | "cssnano": "^3.10.0", 20 | "curvejs": "^0.3.3", 21 | "element-ui": "^1.3.5", 22 | "extract-text-webpack-plugin": "^2.1.0", 23 | "file-loader": "^0.11.1", 24 | "html-webpack-plugin": "^2.28.0", 25 | "lodash": "^4.17.4", 26 | "moment": "^2.18.1", 27 | "opn": "^5.0.0", 28 | "postcss-loader": "^2.0.3", 29 | "style-loader": "^0.16.1", 30 | "url-loader": "^0.5.8", 31 | "vue": "^2.2.6", 32 | "vue-loader": "^11.3.3", 33 | "vue-style-loader": "^3.0.1", 34 | "vue-template-compiler": "^2.2.6", 35 | "webpack": "^2.6.1", 36 | "webpack-dev-server": "^2.4.2", 37 | "webpack-merge": "^4.1.0" 38 | }, 39 | "scripts": { 40 | "dev": "node build/dev.js", 41 | "build": "node build/prod.js" 42 | }, 43 | "keywords": [], 44 | "author": "linuxGithub", 45 | "license": "ISC" 46 | } 47 | -------------------------------------------------------------------------------- /front/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: [ 3 | require('autoprefixer'), 4 | require('cssnano') 5 | ] 6 | }; -------------------------------------------------------------------------------- /front/src/App.vue: -------------------------------------------------------------------------------- 1 | 23 | 24 | 45 | 46 | -------------------------------------------------------------------------------- /front/src/components/DbFilterinput.vue: -------------------------------------------------------------------------------- 1 | 25 | 26 | -------------------------------------------------------------------------------- /front/src/components/DbFooter.vue: -------------------------------------------------------------------------------- 1 | 29 | 30 | 63 | 64 | -------------------------------------------------------------------------------- /front/src/components/DbHeader.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 20 | 21 | -------------------------------------------------------------------------------- /front/src/components/DbModal.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /front/src/components/DbSidebar.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 17 | 18 | 23 | -------------------------------------------------------------------------------- /front/src/components/DbTable.vue: -------------------------------------------------------------------------------- 1 | 26 | 27 | 105 | 106 | -------------------------------------------------------------------------------- /front/src/eventBus.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | const Bus = new Vue(); 3 | export default Bus -------------------------------------------------------------------------------- /front/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import { 3 | Button, 4 | Select, 5 | Row, 6 | Col, 7 | Pagination, 8 | Table, 9 | TableColumn, 10 | Form, 11 | FormItem, 12 | Input, 13 | Dialog, 14 | Option 15 | } from 'element-ui' 16 | import App from './App.vue' 17 | import VueRouter from "vue-router"; 18 | import VueResource from 'vue-resource'; 19 | import 'element-ui/lib/theme-default/index.css' 20 | import lang from 'element-ui/lib/locale/lang/zh-CN' 21 | import locale from 'element-ui/lib/locale' 22 | 23 | // more grace import third package ! 24 | import moment from 'moment' 25 | import axios from 'axios' 26 | import curvejs from 'curvejs' 27 | 28 | Object.defineProperty(Vue.prototype, '$moment', { value: moment }); 29 | Object.defineProperty(Vue.prototype, '$axios', { value: axios }); 30 | Object.defineProperty(Vue.prototype, '$curvejs', { value: curvejs }); 31 | 32 | Vue.use(VueResource); 33 | Vue.use(VueRouter); 34 | Vue.http.options.emulateJSON = true; 35 | 36 | Vue.use(Button); 37 | Vue.use(Select); 38 | Vue.use(Row); 39 | Vue.use(Col); 40 | Vue.use(Pagination); 41 | Vue.use(Table); 42 | Vue.use(TableColumn); 43 | Vue.use(Form); 44 | Vue.use(FormItem); 45 | Vue.use(Input); 46 | Vue.use(Dialog); 47 | Vue.use(Option); 48 | 49 | locale.use(lang); 50 | 51 | 52 | 53 | // eslint-disable-next-line no-new 54 | //new Vue({ 55 | // el: '#app', 56 | // render: h => h(App) 57 | //}); 58 | 59 | var vm =new Vue({ 60 | el: '#app', 61 | router:new VueRouter({ 62 | routes:[ 63 | { path: '/', redirect: 'persons' }, 64 | { path: '/persons', name:'persons', component: App}, 65 | ] 66 | }) 67 | }); 68 | 69 | -------------------------------------------------------------------------------- /gzip.conf: -------------------------------------------------------------------------------- 1 | gzip on; 2 | gzip_min_length 1k; 3 | gzip_buffers 4 16k; 4 | #gzip_http_version 1.0; 5 | gzip_comp_level 2; 6 | gzip_types text/plain application/x-javascript application/json text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; 7 | gzip_vary off; 8 | gzip_disable "MSIE [1-6]\."; -------------------------------------------------------------------------------- /nginx.conf: -------------------------------------------------------------------------------- 1 | #Nginx所用用户和组,window下不指定 2 | #user niumd niumd; 3 | #工作的子进程数量(通常等于CPU数量或者2倍于CPU) 4 | worker_processes 2; 5 | #错误日志存放路径 6 | #error_log logs/error.log; 7 | #error_log logs/error.log notice; 8 | error_log logs/error.log info; 9 | #指定pid存放文件 10 | pid logs/nginx.pid; 11 | events { 12 | #使用网络IO模型linux建议epoll,FreeBSD建议采用kqueue,window下不指定。 13 | #use epoll; 14 | #允许最大连接数 15 | worker_connections 1024; 16 | } 17 | http { 18 | #文件扩展名与文件类型映射表 19 | include mime.types; 20 | 21 | #默认文件类型 22 | default_type application/octet-stream; 23 | 24 | #默认编码 25 | charset utf-8; 26 | 27 | #定义日志格式 28 | log_format main '$remote_addr - $remote_user [$time_local] $request ' 29 | '"$status" $body_bytes_sent "$http_referer" ' 30 | '"$http_user_agent" "$http_x_forwarded_for $request_time $upstream_response_time $upstream_addr $upstream_status"'; 31 | 32 | ###############日志参数的意思对应表####################################################### 33 | #$remote_addr 与$http_x_forwarded_for 用以记录客户端的ip地址; 34 | #$remote_user :用来记录客户端用户名称; 35 | #$time_local :用来记录访问时间与时区; 36 | #$request :用来记录请求的url与http协议; 37 | #$status :用来记录请求状态; 38 | #$body_bytes_sent :记录发送给客户端文件主体内容大小; 39 | #$http_referer :用来记录从那个页面链接访问过来的; 40 | #$http_user_agent :记录客户端浏览器的相关信息;。 41 | #$request_time :响应数据的时间 42 | #$upstream_response_time: 是指从Nginx向后端(php-cgi)建立连接开始到接受完数据然后关闭连接为止的时间。 43 | #$upstream_addr: 后台upstream的地址,即真正提供服务的主机地址 44 | #access_log off; 45 | 46 | access_log logs/access.log main; 47 | client_header_timeout 3m; 48 | client_body_timeout 3m; 49 | send_timeout 3m; 50 | #分页大小可以用命令getconf PAGESIZE 取得。 51 | #但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。 52 | client_header_buffer_size 32k; 53 | 54 | #客户请求头缓冲大小。nginx默认会用client_header_buffer_size这个buffer来读取header值,如果header过大,它会使用large_client_header_buffers来读取。 55 | large_client_header_buffers 4 64k; 56 | 57 | #sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。 58 | sendfile on; 59 | tcp_nopush on; 60 | tcp_nodelay on; 61 | keepalive_timeout 75 20; 62 | 63 | #gzip配置 64 | include gzip.conf; 65 | 66 | #负载均衡配置 67 | upstream proxy_server { 68 | #根据ip计算将请求分配各那个后端tomcat,许多人误认为可以解决session问题,其实并不能。 69 | #ip_hash;#同一机器在多网情况下,路由切换,ip可能不同, ip_hash 不支持backup 70 | server localhost:8000 weight=4 max_fails=2 fail_timeout=30s; 71 | server localhost:9000 weight=6 max_fails=2 fail_timeout=30s; 72 | server localhost:8888 backup; 73 | keepalive 300; 74 | } 75 | 76 | #访问nginx自带的页面nginx首页地址:http://www.nginxserver.com:8080/ 77 | server { 78 | listen 8080; 79 | server_name www.nginxserver.com; 80 | index index.html index.htm; 81 | root html; 82 | 83 | location ~ .*\.(html|htm)?$ { 84 | 85 | } 86 | 87 | location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ { 88 | expires 30s; 89 | } 90 | 91 | #expires 30s; //表示把数据缓存30秒 92 | #expires 30m;//表示把数据缓存30分 93 | #expires 10h;//表示把数据缓存10小时 94 | #expires 1d;//表示把数据缓存1天 95 | 96 | location ~ .*\.(js|css)?$ { 97 | expires 30s; 98 | } 99 | } 100 | 101 | #通过代理访问后台的服务器:http://www.nginxserver.com/ 102 | server { 103 | listen 80; 104 | server_name www.nginxserver.com; 105 | index index.html index.htm; 106 | root html; 107 | 108 | location / { 109 | proxy_pass http://proxy_server; 110 | 111 | #proxy config 112 | proxy_redirect off; 113 | proxy_set_header Host $host:$server_port; 114 | proxy_set_header X-Real-IP $remote_addr; 115 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 116 | client_max_body_size 10m; 117 | client_body_buffer_size 128k; 118 | proxy_connect_timeout 300s; 119 | proxy_send_timeout 300s; 120 | proxy_read_timeout 300s; 121 | proxy_buffer_size 4k; 122 | proxy_buffers 4 32k; 123 | proxy_busy_buffers_size 64k; 124 | proxy_temp_file_write_size 64k; 125 | proxy_http_version 1.1; 126 | } 127 | 128 | #设定查看Nginx状态的地址 129 | location /NginxStatus { 130 | stub_status on; 131 | access_log on; 132 | auth_basic "NginxStatus Login"; 133 | #https://www.cnblogs.com/AloneSword/p/5086918.html 134 | auth_basic_user_file htpasswd;#htpasswd文件的内容可以用apache提供的htpasswd工具来产生。 135 | allow 127.0.0.1; # 白名单 136 | allow 10.1.51.96; # 白名单 137 | deny all; #禁止其他的地址访问 138 | } 139 | 140 | #加入了一下配置后,既可以通过8080端口访问nginx的首页, 也可以通过80端口访问nginx首页 141 | location ~ .*\.(html|htm)?$ { 142 | } 143 | location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ { 144 | expires 30s; 145 | } 146 | location ~ .*\.(js|css)?$ { 147 | expires 30s; 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ninuxGithub/spring-boot-vue-separate/b44afd75241e8c44ab55e38027b76b7a6ec0e287/pic.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | spring-boot-vue-separate 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-vue-separate 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.2.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | mysql 38 | mysql-connector-java 39 | 40 | 41 | com.zaxxer 42 | HikariCP 43 | compile 44 | 45 | 46 | org.xson 47 | xson 48 | 1.0.2 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-test 53 | test 54 | 55 | 59 | 60 | org.projectlombok 61 | lombok 62 | 63 | 64 | 65 | com.google.code.gson 66 | gson 67 | 68 | 69 | 70 | org.apache.poi 71 | poi-ooxml 72 | 3.9 73 | 74 | 75 | 76 | com.xiaoleilu 77 | hutool 78 | 2.10.1 79 | 80 | 81 | commons-lang 82 | commons-lang 83 | 2.6 84 | 85 | 86 | commons-fileupload 87 | commons-fileupload 88 | 1.3.1 89 | 90 | 91 | commons-io 92 | commons-io 93 | 2.4 94 | 95 | 96 | 97 | org.springframework.boot 98 | spring-boot-starter-actuator 99 | 100 | 101 | 102 | 103 | jfree 104 | jfreechart 105 | 1.0.11 106 | 107 | 108 | gnujaxp 109 | gnujaxp 110 | 1.0.0 111 | 112 | 113 | jfree 114 | jcommon 115 | 1.0.14 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | commons-codec 134 | commons-codec 135 | 1.10 136 | 137 | 138 | 139 | com.belerweb 140 | pinyin4j 141 | 2.5.0 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | org.springframework.boot 177 | spring-boot-maven-plugin 178 | 179 | 180 | true 181 | 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-surefire-plugin 187 | 188 | true 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/Application.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.CommandLineRunner; 8 | import org.springframework.boot.SpringApplication; 9 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 10 | import org.springframework.boot.autoconfigure.SpringBootApplication; 11 | import org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration; 12 | import org.springframework.boot.web.servlet.ServletComponentScan; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.context.annotation.Configuration; 15 | import org.springframework.web.multipart.MultipartResolver; 16 | import org.springframework.web.multipart.commons.CommonsMultipartResolver; 17 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 18 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 19 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 20 | 21 | import com.example.demo.bean.Persons; 22 | import com.example.demo.component.CustomMultipartResolver; 23 | import com.example.demo.repository.PersonsRepository; 24 | 25 | @SpringBootApplication 26 | @Configuration 27 | @ServletComponentScan 28 | @EnableAutoConfiguration(exclude = { MultipartAutoConfiguration.class }) 29 | public class Application implements CommandLineRunner { 30 | 31 | public static void main(String[] args) { 32 | SpringApplication.run(Application.class, args); 33 | } 34 | 35 | /** 36 | * 允许vue http 跨域访问springmvc controller api 37 | * 38 | * @return 39 | */ 40 | // 在前台设置了跨域访问 41 | // 42 | // @Bean 43 | // public WebMvcConfigurer corsConfigurer() { 44 | // return new WebMvcConfigurerAdapter() { 45 | // @Override 46 | // public void addCorsMappings(CorsRegistry registry) { 47 | // registry.addMapping("/**").allowedOrigins(ALL).allowedMethods(ALL).allowedHeaders(ALL) 48 | // .allowCredentials(true); 49 | // } 50 | // }; 51 | // } 52 | 53 | @Bean(name = "multipartResolver") 54 | public MultipartResolver multipartResolver() { 55 | CommonsMultipartResolver resolver = new CustomMultipartResolver(); 56 | resolver.setDefaultEncoding("UTF-8"); 57 | resolver.setResolveLazily(true);// resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常 58 | resolver.setMaxInMemorySize(40960); 59 | resolver.setMaxUploadSize(50 * 1024 * 1024);// 上传文件大小 5M 5*1024*1024 60 | return resolver; 61 | } 62 | 63 | @Autowired 64 | private PersonsRepository personRepository; 65 | 66 | @Override 67 | public void run(String... args) throws Exception { 68 | // initPersonTable(); 69 | } 70 | 71 | /** 72 | * 初始化Persons 表格 73 | */ 74 | public void initPersonTable() { 75 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 76 | for (int i = 0; i < 15; i++) { 77 | Persons p = new Persons(); 78 | p.setEmail("12345" + i + "@qq.com"); 79 | p.setCreate_datetime(dateFormat.format(new Date())); 80 | p.setPhone("798374" + i); 81 | p.setSex(i % 2 == 0 ? "男" : "女"); 82 | p.setUsername("text" + i); 83 | p.setZone("D8"); 84 | personRepository.save(p); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/PageNumber.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.PageImpl; 7 | import org.springframework.data.domain.PageRequest; 8 | import org.springframework.data.domain.Pageable; 9 | 10 | public class PageNumber extends PageImpl implements Page { 11 | 12 | /** 13 | * 14 | */ 15 | private static final long serialVersionUID = 4457024920612570312L; 16 | 17 | /** 18 | * 前台传参1为起始页修改为spring data jpa的0为起始页 19 | * 20 | * @param pageable 21 | * @return 22 | */ 23 | public static Pageable pageRequest(Pageable pageable) { 24 | return new PageRequest(pageable.getPageNumber() - 1, pageable.getPageSize(), pageable.getSort()); 25 | } 26 | 27 | /** 28 | * Constructor of {@code PageImpl}. 29 | * 30 | * @param content 31 | * the content of this page, must not be {@literal null}. 32 | * @param pageable 33 | * the paging information, can be {@literal null}. 34 | * @param total 35 | * the total amount of items available. The total might be adapted 36 | * considering the length of the content 37 | */ 38 | public PageNumber(List content, Pageable pageable, long total) { 39 | super(content, pageable, total); 40 | } 41 | 42 | /** 43 | * 重写当前页,将当前页加1返回前台,spring data jpa起始页0加1后返回前台 44 | * 45 | * @return 46 | */ 47 | @Override 48 | public int getNumber() { 49 | return super.getNumber() + 1; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/Persons.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | @Entity 7 | @Table(name = "persons") 8 | public class Persons implements Serializable { 9 | 10 | private static final long serialVersionUID = 8538436285933130519L; 11 | 12 | @Id 13 | @GeneratedValue(strategy = GenerationType.AUTO) 14 | private Long id; 15 | 16 | @Column(name = "create_datetime") 17 | private String create_datetime; 18 | 19 | @Column(name = "username") 20 | private String username; 21 | 22 | @Column(name = "email") 23 | private String email; 24 | 25 | @Column(name = "phone") 26 | private String phone; 27 | 28 | @Column(name = "sex") 29 | private String sex; 30 | 31 | @Column(name = "zone") 32 | private String zone; 33 | 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public String getCreate_datetime() { 43 | return create_datetime; 44 | 45 | } 46 | 47 | public void setCreate_datetime(String create_datetime) { 48 | this.create_datetime = create_datetime; 49 | } 50 | 51 | public String getUsername() { 52 | return username; 53 | } 54 | 55 | public void setUsername(String username) { 56 | this.username = username; 57 | } 58 | 59 | public String getEmail() { 60 | return email; 61 | } 62 | 63 | public void setEmail(String email) { 64 | this.email = email; 65 | } 66 | 67 | public String getPhone() { 68 | return phone; 69 | } 70 | 71 | public void setPhone(String phone) { 72 | this.phone = phone; 73 | } 74 | 75 | public String getSex() { 76 | return sex; 77 | } 78 | 79 | public void setSex(String sex) { 80 | this.sex = sex; 81 | } 82 | 83 | public String getZone() { 84 | return zone; 85 | } 86 | 87 | public void setZone(String zone) { 88 | this.zone = zone; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return "Persons [id=" + id + ", create_datetime=" + create_datetime + ", username=" + username + ", email=" 94 | + email + ", phone=" + phone + ", sex=" + sex + ", zone=" + zone + "]"; 95 | } 96 | 97 | 98 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/Progress.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | public class Progress { 4 | private long pBytesRead; 5 | private long pContentLength; 6 | private long pItems; 7 | 8 | public long getpBytesRead() { 9 | return pBytesRead; 10 | } 11 | 12 | public void setpBytesRead(long pBytesRead) { 13 | this.pBytesRead = pBytesRead; 14 | } 15 | 16 | public long getpContentLength() { 17 | return pContentLength; 18 | } 19 | 20 | public void setpContentLength(long pContentLength) { 21 | this.pContentLength = pContentLength; 22 | } 23 | 24 | public long getpItems() { 25 | return pItems; 26 | } 27 | 28 | public void setpItems(long pItems) { 29 | this.pItems = pItems; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "Progress [pBytesRead=" + pBytesRead + ", pContentLength=" + pContentLength + ", pItems=" + pItems + "]"; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/SelectCondition.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import java.io.Serializable; 4 | 5 | public class SelectCondition implements Serializable { 6 | 7 | private static final long serialVersionUID = -1615064653013084687L; 8 | 9 | private Long id; 10 | private String content; 11 | 12 | 13 | 14 | public Long getId() { 15 | return id; 16 | } 17 | 18 | public void setId(Long id) { 19 | this.id = id; 20 | } 21 | 22 | public String getContent() { 23 | return content; 24 | } 25 | 26 | public void setContent(String content) { 27 | this.content = content; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/Student.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | import lombok.AllArgsConstructor; 12 | import lombok.Data; 13 | import lombok.NoArgsConstructor; 14 | 15 | @Data 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @Entity 19 | @Table(name = "student") 20 | public class Student implements Serializable { 21 | 22 | public Student(String id, String name, String number, Double score) { 23 | this.id=id; 24 | this.name=name; 25 | this.number=number; 26 | this.score=score; 27 | 28 | } 29 | private static final long serialVersionUID = 2281693583701708108L; 30 | /** 学生ID */ 31 | @Id 32 | private String id; 33 | /** 学生姓名 */ 34 | private String name; 35 | /** 序号 */ 36 | private String number; 37 | /** 分数 */ 38 | private Double score; 39 | /** 创建时间 */ 40 | @Column(name="create_time") 41 | private Date createTime; 42 | /** 爱好 */ 43 | private String hobby; 44 | /**是否激活*/ 45 | private Integer active; 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/TreeNode.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import java.io.Serializable; 4 | import java.util.List; 5 | 6 | import javax.persistence.CascadeType; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.Id; 12 | import javax.persistence.JoinColumn; 13 | import javax.persistence.ManyToOne; 14 | import javax.persistence.OneToMany; 15 | import javax.persistence.OrderBy; 16 | import javax.persistence.Table; 17 | 18 | import org.hibernate.annotations.Fetch; 19 | import org.hibernate.annotations.FetchMode; 20 | import org.hibernate.annotations.GenericGenerator; 21 | 22 | /** 23 | * 构建树形结构 24 | * 25 | * JAP 对象自己引用自己的Demo 26 | * 27 | */ 28 | 29 | @Entity 30 | @Table(name = "tree_node") 31 | public class TreeNode implements Serializable { 32 | 33 | private static final long serialVersionUID = 6685482681822159077L; 34 | @Id 35 | @GenericGenerator(name = "idGenerator", strategy = "uuid") // 这个是hibernate的注解 36 | @GeneratedValue(generator = "idGenerator") // 使用uuid的生成策略 37 | private String id; 38 | 39 | @Column(name="tree_order") 40 | private Integer treeOrder; 41 | 42 | private String label; 43 | 44 | @OneToMany(fetch = FetchType.EAGER,targetEntity = TreeNode.class, cascade = { CascadeType.ALL }, mappedBy = "parent") 45 | @Fetch(FetchMode.SUBSELECT) 46 | @OrderBy("tree_order") 47 | private List children; 48 | 49 | @ManyToOne(fetch = FetchType.EAGER) 50 | @JoinColumn(name = "pid") 51 | private TreeNode parent; 52 | 53 | public TreeNode() { 54 | } 55 | 56 | public TreeNode(Integer treeOrder, String label, TreeNode parent) { 57 | this.treeOrder = treeOrder; 58 | this.label = label; 59 | this.parent = parent; 60 | } 61 | 62 | public String getId() { 63 | return id; 64 | } 65 | 66 | public void setId(String id) { 67 | this.id = id; 68 | } 69 | 70 | public String getLabel() { 71 | return label; 72 | } 73 | 74 | public void setLabel(String label) { 75 | this.label = label; 76 | } 77 | 78 | public List getChildren() { 79 | return children; 80 | } 81 | 82 | public void setChildren(List children) { 83 | this.children = children; 84 | } 85 | 86 | public TreeNode getParent() { 87 | return parent; 88 | } 89 | 90 | public void setParent(TreeNode parent) { 91 | this.parent = parent; 92 | } 93 | 94 | 95 | 96 | 97 | public Integer getTreeOrder() { 98 | return treeOrder; 99 | } 100 | 101 | public void setTreeOrder(Integer treeOrder) { 102 | this.treeOrder = treeOrder; 103 | } 104 | 105 | 106 | 107 | @Override 108 | public String toString() { 109 | // System.out.println(this.id); 110 | // System.out.println(this.treeOrder); 111 | // System.out.println(this.label); 112 | // System.out.println(this.children); 113 | return "{id=" + id + ", treeOrder=" + treeOrder + ", label=" + label + ", children=" + children+ "}"; 114 | } 115 | 116 | @Override 117 | public int hashCode() { 118 | final int prime = 31; 119 | int result = 1; 120 | result = prime * result + ((children == null) ? 0 : children.hashCode()); 121 | result = prime * result + ((id == null) ? 0 : id.hashCode()); 122 | result = prime * result + ((label == null) ? 0 : label.hashCode()); 123 | result = prime * result + ((treeOrder == null) ? 0 : treeOrder.hashCode()); 124 | result = prime * result + ((parent == null) ? 0 : parent.hashCode()); 125 | return result; 126 | } 127 | 128 | @Override 129 | public boolean equals(Object obj) { 130 | if (this == obj) 131 | return true; 132 | if (obj == null) 133 | return false; 134 | if (getClass() != obj.getClass()) 135 | return false; 136 | TreeNode other = (TreeNode) obj; 137 | if (children == null) { 138 | if (other.children != null) 139 | return false; 140 | } else if (!children.equals(other.children)) 141 | return false; 142 | if (id == null) { 143 | if (other.id != null) 144 | return false; 145 | } else if (!id.equals(other.id)) 146 | return false; 147 | if (label == null) { 148 | if (other.label != null) 149 | return false; 150 | } else if (!label.equals(other.label)) 151 | return false; 152 | if (treeOrder == null) { 153 | if (other.treeOrder != null) 154 | return false; 155 | } else if (!treeOrder.equals(other.treeOrder)) 156 | return false; 157 | if (parent == null) { 158 | if (other.parent != null) 159 | return false; 160 | } else if (!parent.equals(other.parent)) 161 | return false; 162 | return true; 163 | } 164 | 165 | } 166 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/bean/User.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.bean; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | @Entity 12 | @Table(name = "user_table") 13 | public class User implements Serializable { 14 | private static final long serialVersionUID = 5954252966400830349L; 15 | 16 | @Id 17 | // @GeneratedValue(strategy = GenerationType.AUTO) 18 | private String id; 19 | private String username; 20 | private String name; 21 | private String phone; 22 | private String email; 23 | @Column(name = "create_time") 24 | private Date createTime; 25 | 26 | private boolean is_active; 27 | private String checkpass; 28 | 29 | public User() { 30 | } 31 | 32 | public User(String id, String username, String name, String phone, String email, Date create_time, boolean is_active, 33 | String checkpass) { 34 | this.id = id; 35 | this.username = username; 36 | this.name = name; 37 | this.phone = phone; 38 | this.email = email; 39 | this.createTime = create_time; 40 | this.is_active = is_active; 41 | this.checkpass = checkpass; 42 | } 43 | 44 | public String getUsername() { 45 | return username; 46 | } 47 | 48 | public void setUsername(String username) { 49 | this.username = username; 50 | } 51 | 52 | public String getName() { 53 | return name; 54 | } 55 | 56 | public void setName(String name) { 57 | this.name = name; 58 | } 59 | 60 | public String getPhone() { 61 | return phone; 62 | } 63 | 64 | public void setPhone(String phone) { 65 | this.phone = phone; 66 | } 67 | 68 | public String getEmail() { 69 | return email; 70 | } 71 | 72 | public void setEmail(String email) { 73 | this.email = email; 74 | } 75 | 76 | public Date getCreateTime() { 77 | return createTime; 78 | } 79 | 80 | public void setCreateTime(Date createTime) { 81 | this.createTime = createTime; 82 | } 83 | 84 | public void setId(String id) { 85 | this.id = id; 86 | } 87 | 88 | public void setIs_active(boolean is_active) { 89 | this.is_active = is_active; 90 | } 91 | 92 | public void setCheckpass(String checkpass) { 93 | this.checkpass = checkpass; 94 | } 95 | 96 | public String getId() { 97 | return id; 98 | } 99 | 100 | public boolean getIs_active() { 101 | return is_active; 102 | } 103 | 104 | public String getCheckpass() { 105 | return checkpass; 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/commandline/InitTreeNode.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.commandline; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.CommandLineRunner; 9 | import org.springframework.stereotype.Service; 10 | 11 | import com.example.demo.bean.TreeNode; 12 | import com.example.demo.repository.TreeNodeRepository; 13 | import com.xiaoleilu.hutool.CollectionUtil; 14 | 15 | @Service 16 | public class InitTreeNode implements CommandLineRunner { 17 | 18 | private AtomicInteger orderNum = new AtomicInteger(0); 19 | 20 | @Autowired 21 | private TreeNodeRepository treeNodeRepository; 22 | 23 | @Override 24 | public void run(String... args) throws Exception { 25 | List levelOneList = treeNodeRepository.findAll(); 26 | 27 | if(CollectionUtil.isEmpty(levelOneList)) { 28 | System.err.println("init Tree Node..."); 29 | levelOneList = new LinkedList<>(); 30 | List levelTwoList= new LinkedList<>(); 31 | List levelThreeList = new LinkedList<>(); 32 | 33 | String arr[] = new String[] {"管理层","销售层","开发层"}; 34 | for (int i = 0; i < arr.length; i++) { 35 | TreeNode levelOne = new TreeNode(orderNum.getAndIncrement(), arr[i], null); 36 | for(int j=0; j<3; j++) { 37 | TreeNode levelTwo = new TreeNode(orderNum.getAndIncrement(), arr[i]+"-"+ j, levelOne); 38 | levelTwoList.add(levelTwo); 39 | 40 | if(j==0) { 41 | for(int k=0; k<2; k++) { 42 | TreeNode levelThree = new TreeNode(orderNum.getAndIncrement(), arr[i]+"-"+ j+"-"+k, levelTwo); 43 | levelThreeList.add(levelThree); 44 | } 45 | } 46 | levelTwo.setChildren(levelThreeList); 47 | } 48 | 49 | levelOne.setChildren(levelTwoList); 50 | levelOneList.add(levelOne);//第一层的树 51 | } 52 | 53 | 54 | try { 55 | List save = treeNodeRepository.save(levelOneList); 56 | 57 | System.out.println(save); 58 | 59 | List treeNodeList = treeNodeRepository.findAll(); 60 | System.out.println(treeNodeList); 61 | } catch (Exception e) { 62 | // TODO Auto-generated catch block 63 | e.printStackTrace(); 64 | } 65 | 66 | 67 | } 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/commandline/TestConcurrentHashMap.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.commandline; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public class TestConcurrentHashMap { 7 | public static void main(String[] args) { 8 | Map map = new ConcurrentHashMap<>(2); 9 | map.put("aaa", "aa"); 10 | map.put("aaa1", "aa"); 11 | map.put("aaa2", "aa"); 12 | map.put("aaa3", "aa"); 13 | map.put("aaa4", "aa"); 14 | map.put("aaa5", "aa"); 15 | map.put("aaa6", "aa"); 16 | 17 | System.out.println(map); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/component/CustomMultipartResolver.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.component; 2 | 3 | import java.util.List; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.apache.commons.fileupload.FileItem; 8 | import org.apache.commons.fileupload.FileUpload; 9 | import org.apache.commons.fileupload.FileUploadBase; 10 | import org.apache.commons.fileupload.FileUploadException; 11 | import org.apache.commons.fileupload.servlet.ServletFileUpload; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.web.multipart.MaxUploadSizeExceededException; 14 | import org.springframework.web.multipart.MultipartException; 15 | import org.springframework.web.multipart.commons.CommonsMultipartResolver; 16 | 17 | public class CustomMultipartResolver extends CommonsMultipartResolver { 18 | @Autowired 19 | private FileUploadProgressListener progressListener; 20 | 21 | public void setFileUploadProgressListener(FileUploadProgressListener progressListener) { 22 | this.progressListener = progressListener; 23 | } 24 | 25 | @Override 26 | public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException { 27 | String encoding = determineEncoding(request); 28 | FileUpload fileUpload = prepareFileUpload(encoding); 29 | progressListener.setSession(request.getSession()); 30 | fileUpload.setProgressListener(progressListener); 31 | try { 32 | List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); 33 | return parseFileItems(fileItems, encoding); 34 | } catch (FileUploadBase.SizeLimitExceededException ex) { 35 | throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); 36 | } catch (FileUploadException ex) { 37 | throw new MultipartException("Could not parse multipart servlet request", ex); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/component/FileUploadProgressListener.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.component; 2 | 3 | import javax.servlet.http.HttpSession; 4 | 5 | import org.apache.commons.fileupload.ProgressListener; 6 | import org.springframework.stereotype.Component; 7 | 8 | import com.example.demo.bean.Progress; 9 | 10 | @Component 11 | public class FileUploadProgressListener implements ProgressListener { 12 | private HttpSession session; 13 | 14 | public void setSession(HttpSession session) { 15 | this.session = session; 16 | Progress status = new Progress();// 保存上传状态 17 | session.setAttribute("status", status); 18 | } 19 | 20 | @Override 21 | public void update(long pBytesRead, long pContentLength, int pItems) { 22 | Progress status = (Progress) session.getAttribute("status"); 23 | try { 24 | Thread.sleep(5); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | status.setpBytesRead(pBytesRead); 29 | status.setpContentLength(pContentLength); 30 | status.setpItems(pItems); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/component/SpringContext.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.component; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.beans.BeansException; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.ApplicationContextAware; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class SpringContext implements ApplicationContextAware { 12 | 13 | private static final Logger logger = LoggerFactory.getLogger(SpringContext.class); 14 | 15 | private static ApplicationContext springContext = null; 16 | 17 | @Override 18 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 19 | springContext = applicationContext; 20 | logger.info("init SpringContext..."); 21 | 22 | } 23 | 24 | public ApplicationContext getSpringContext() { 25 | return springContext; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/component/WebmvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.component; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 5 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 6 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 7 | 8 | import com.example.demo.interceptor.InterceptorDemo; 9 | 10 | @Configuration 11 | public class WebmvcConfig extends WebMvcConfigurerAdapter { 12 | 13 | @Override 14 | public void addInterceptors(InterceptorRegistry registry) { 15 | super.addInterceptors(registry); 16 | registry.addInterceptor(new InterceptorDemo()).addPathPatterns("/api/**"); 17 | } 18 | 19 | @Override 20 | public void addCorsMappings(CorsRegistry registry) { 21 | registry.addMapping("/api/**").allowedOrigins("http://localhost:8888"); 22 | //registry.addMapping("/api/**").allowedOrigins("http://localhost:8888"); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import javax.persistence.criteria.CriteriaBuilder; 8 | import javax.persistence.criteria.CriteriaQuery; 9 | import javax.persistence.criteria.Predicate; 10 | import javax.persistence.criteria.Root; 11 | 12 | import org.apache.commons.lang.StringUtils; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.beans.factory.annotation.Value; 17 | import org.springframework.data.domain.Page; 18 | import org.springframework.data.domain.PageRequest; 19 | import org.springframework.data.domain.Pageable; 20 | import org.springframework.data.domain.Sort; 21 | import org.springframework.data.domain.Sort.Direction; 22 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 23 | import org.springframework.stereotype.Controller; 24 | 25 | import com.example.demo.bean.PageNumber; 26 | import com.example.demo.utils.SpringUtil; 27 | 28 | @Controller 29 | public class BaseController { 30 | 31 | private static final Logger logger = LoggerFactory.getLogger(BaseController.class); 32 | 33 | /** 分页默认的每页页数 */ 34 | @Value(("${paginatio.max-per-page}")) 35 | protected Integer maxPerPage; 36 | 37 | @Autowired 38 | private SpringUtil springUtil; 39 | 40 | /** 41 | * @param page 42 | * 第几页 43 | * @param perPage 44 | * 每页的记录条数 45 | * @param sortType 46 | * 排序的字段 47 | * @param params 48 | * 排序的map 49 | * @param beanClass 50 | * bean对应的repository 51 | * @return 52 | */ 53 | @SuppressWarnings({ "static-access", "unchecked" }) 54 | public Page queryPagination(Integer page, Integer perPage, String sortType, Map params, Class beanClass) { 55 | if(beanClass ==null) { 56 | throw new RuntimeException("[queryPagination] beanClass is required!"); 57 | } 58 | if (page == null) { 59 | page = 1; 60 | } 61 | Sort sort ; 62 | Direction direction = Direction.ASC; 63 | if (StringUtils.isBlank(sortType)) { 64 | sort = new Sort(direction, "id"); 65 | } else { 66 | if (sortType.startsWith("-")) { 67 | direction = Direction.DESC; 68 | sortType = sortType.substring(1); 69 | } 70 | sort = new Sort(direction, sortType); 71 | } 72 | // 创建pageable对象 73 | Pageable pageable = new PageRequest(page - 1, perPage == null ? maxPerPage : perPage, sort); 74 | // 开始获取分页的JpaSpecificationExecutor 75 | JpaSpecificationExecutor bean = (JpaSpecificationExecutor) springUtil.getBean(beanClass); 76 | logger.info("sort field :{} queryPagination run...", sortType); 77 | // 开始分页 78 | //Lambda 79 | Page pagination = bean.findAll((Root root, CriteriaQuery query, CriteriaBuilder cb)->{ 80 | List predicatList = new ArrayList<>(); 81 | for (String field : params.keySet()) { 82 | Object value = params.get(field); 83 | if (null != value && StringUtils.isNotBlank(value.toString())) { 84 | //有些字段是不可以采用like的 例如Double ... 85 | predicatList.add(cb.like(root.get(field), "%" + value + "%")); 86 | } 87 | } 88 | Predicate[] arrayPredicates = new Predicate[predicatList.size()]; 89 | return cb.and(predicatList.toArray(arrayPredicates)); 90 | },pageable); 91 | 92 | 93 | /* 94 | Page pagination = bean.findAll(new Specification() { 95 | @Override 96 | public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { 97 | List predicatList = new ArrayList<>(); 98 | for (String field : params.keySet()) { 99 | Object value = params.get(field); 100 | if (null != value && StringUtils.isNotBlank(value.toString())) { 101 | //有些字段是不可以采用like的 例如Double ... 102 | predicatList.add(cb.like(root.get(field), "%" + value + "%")); 103 | } 104 | } 105 | Predicate[] arrayPredicates = new Predicate[predicatList.size()]; 106 | return cb.and(predicatList.toArray(arrayPredicates)); 107 | } 108 | }, pageable); 109 | */ 110 | // 对分页的PageNumber 进行调整 111 | return new PageNumber<>(pagination.getContent(), pageable, pagination.getTotalElements()); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/FileUploadController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RequestMethod; 12 | import org.springframework.web.bind.annotation.RequestParam; 13 | import org.springframework.web.multipart.commons.CommonsMultipartFile; 14 | 15 | import com.example.demo.utils.FileUploadUtil; 16 | 17 | @Controller 18 | public class FileUploadController { 19 | 20 | @RequestMapping(value = "/upload", method = { RequestMethod.GET, RequestMethod.POST }) 21 | public void upload(HttpServletRequest request, HttpServletResponse response, 22 | @RequestParam(value = "file", required = false) CommonsMultipartFile file) { 23 | response.setContentType("text/html"); 24 | response.setCharacterEncoding("GBK"); 25 | PrintWriter out = null; 26 | boolean flag = false; 27 | if (file.getSize() > 0) { 28 | // 文件上传的位置可以自定义 29 | flag = FileUploadUtil.uploadFile(request, file); 30 | String name = file.getName(); 31 | System.out.println("上传文件的名称为:" + name); 32 | } 33 | try { 34 | out = response.getWriter(); 35 | } catch (IOException e) { 36 | e.printStackTrace(); 37 | } 38 | if (flag == true) { 39 | out.print("1"); 40 | } else { 41 | out.print("2"); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/MainController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.persistence.criteria.CriteriaBuilder; 9 | import javax.persistence.criteria.CriteriaQuery; 10 | import javax.persistence.criteria.Predicate; 11 | import javax.persistence.criteria.Root; 12 | import javax.servlet.http.HttpSession; 13 | 14 | import org.apache.commons.lang.StringUtils; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Autowired; 18 | import org.springframework.beans.factory.annotation.Value; 19 | import org.springframework.data.domain.Page; 20 | import org.springframework.data.domain.PageRequest; 21 | import org.springframework.data.domain.Pageable; 22 | import org.springframework.data.domain.Sort; 23 | import org.springframework.data.domain.Sort.Direction; 24 | import org.springframework.data.jpa.domain.Specification; 25 | import org.springframework.http.HttpStatus; 26 | import org.springframework.http.MediaType; 27 | import org.springframework.http.ResponseEntity; 28 | import org.springframework.web.bind.annotation.PathVariable; 29 | import org.springframework.web.bind.annotation.RequestBody; 30 | import org.springframework.web.bind.annotation.RequestMapping; 31 | import org.springframework.web.bind.annotation.RequestMethod; 32 | import org.springframework.web.bind.annotation.RequestParam; 33 | import org.springframework.web.bind.annotation.RestController; 34 | 35 | import com.example.demo.bean.PageNumber; 36 | import com.example.demo.bean.Persons; 37 | import com.example.demo.repository.PersonsRepository; 38 | 39 | @RestController 40 | @RequestMapping("/api/persons") 41 | public class MainController { 42 | 43 | private static final Logger logger = LoggerFactory.getLogger(MainController.class); 44 | 45 | @Autowired 46 | private PersonsRepository personsRepository; 47 | 48 | @Value(("${paginatio.max-per-page}")) 49 | Integer maxPerPage; 50 | 51 | @RequestMapping(value = "/sex", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 52 | public ResponseEntity getSexAll() { 53 | logger.info("getSexAll"); 54 | ArrayList> results = new ArrayList<>(); 55 | 56 | for (Object value : personsRepository.findSex()) { 57 | 58 | Map sex = new HashMap<>(); 59 | 60 | sex.put("label", value.toString()); 61 | 62 | sex.put("value", value.toString()); 63 | 64 | results.add(sex); 65 | } 66 | 67 | ResponseEntity>> responseEntity = new ResponseEntity<>(results, HttpStatus.OK); 68 | 69 | return responseEntity; 70 | } 71 | 72 | 73 | 74 | @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 75 | public Page jpaSearch(HttpSession session,@RequestParam(value = "page", required = false) Integer page, 76 | @RequestParam(value = "sex",required=false) final String sex, @RequestParam(value="email",required=false) final String email) { 77 | logger.info("jpaSearch"); 78 | if (page == null) { 79 | page = 1; 80 | } 81 | Sort sort = new Sort(Direction.ASC, "id"); 82 | 83 | Pageable pageable = new PageRequest(page - 1, maxPerPage, sort); 84 | 85 | Page pagination = personsRepository.findAll(new Specification() { 86 | @Override 87 | public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) { 88 | List predicatList = new ArrayList<>(); 89 | if (StringUtils.isNotBlank(sex)) { 90 | predicatList.add(cb.like(root.get("sex"), "%" + sex + "%")); 91 | } 92 | if (StringUtils.isNotBlank(email)) { 93 | predicatList.add(cb.like(root.get("email"), "%" + email + "%")); 94 | } 95 | 96 | Predicate[] arrayPredicates = new Predicate[predicatList.size()]; 97 | return cb.and(predicatList.toArray(arrayPredicates)); 98 | } 99 | }, pageable); 100 | 101 | // System.out.println("num:" + pagination.getNumber()); 102 | // System.out.println("size:" + pagination.getSize()); 103 | // System.out.println("content:" + pagination.getContent()); 104 | // System.out.println("total page:" + pagination.getTotalPages()); 105 | // System.out.println("total Elements:" + pagination.getTotalElements()); 106 | // System.out.println("hasNext:" + pagination.hasNext()); 107 | 108 | return new PageNumber<>(pagination.getContent(), pageable, pagination.getTotalElements()); 109 | 110 | } 111 | 112 | @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 113 | public ResponseEntity getUserDetail(@PathVariable Long id) { 114 | 115 | Persons user = personsRepository.findById(id); 116 | 117 | return new ResponseEntity<>(user, HttpStatus.OK); 118 | } 119 | 120 | @RequestMapping(value = "/detail/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) 121 | public Persons updateUser(@PathVariable Long id, @RequestBody Persons data) { 122 | 123 | Persons user = personsRepository.findById(id); 124 | 125 | user.setPhone(data.getPhone()); 126 | 127 | user.setZone(data.getZone()); 128 | 129 | return personsRepository.save(user); 130 | } 131 | 132 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/SelectionConditionController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | 9 | import com.example.demo.bean.SelectCondition; 10 | 11 | @Controller 12 | @RequestMapping("/api") 13 | public class SelectionConditionController { 14 | 15 | 16 | public List loadConditions(){ 17 | List list= new LinkedList<>(); 18 | 19 | return list; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/StudentController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileReader; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.text.SimpleDateFormat; 9 | import java.util.Date; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | import org.apache.commons.lang.StringUtils; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.beans.propertyeditors.CustomDateEditor; 18 | import org.springframework.data.domain.Page; 19 | import org.springframework.http.MediaType; 20 | import org.springframework.web.bind.WebDataBinder; 21 | import org.springframework.web.bind.annotation.InitBinder; 22 | import org.springframework.web.bind.annotation.PathVariable; 23 | import org.springframework.web.bind.annotation.RequestMapping; 24 | import org.springframework.web.bind.annotation.RequestMethod; 25 | import org.springframework.web.bind.annotation.RequestParam; 26 | import org.springframework.web.bind.annotation.RestController; 27 | 28 | import com.example.demo.bean.Student; 29 | import com.example.demo.repository.StudentRepository; 30 | 31 | 32 | @RestController 33 | @RequestMapping(value="/api") 34 | public class StudentController extends BaseController { 35 | 36 | private static final Logger logger = LoggerFactory.getLogger(StudentController.class); 37 | @Autowired 38 | private StudentRepository studentRepository; 39 | 40 | @SuppressWarnings("serial") 41 | @RequestMapping(value = "/studentinfo", method = { RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) 42 | public Page getStudents(@RequestParam(value = "page", required = false) Integer page, 43 | @RequestParam(value = "per_page", required = false) Integer perPage, 44 | @RequestParam(value = "sorts", required = false) String sortType, 45 | @RequestParam(value = "name", required = false) String name, 46 | @RequestParam(value = "number", required = false) String number, 47 | @RequestParam(value = "score", required = false) Double score) { 48 | return queryPagination(page, perPage, sortType, new HashMap() { 49 | { 50 | put("name", name); 51 | put("number", number); 52 | put("score", score); 53 | 54 | } 55 | }, StudentRepository.class); 56 | } 57 | 58 | @RequestMapping(value = "/studentinfo", method = {RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE) 59 | public void saveStudent(@RequestParam(value = "id", required = false) String id, 60 | @RequestParam(value = "name", required = false) String name, 61 | @RequestParam(value = "number", required = false) String number, 62 | @RequestParam(value = "score", required = false) Double score, 63 | @RequestParam(value = "createTime", required = false) Date createTime, 64 | @RequestParam(value = "hobby", required = false) String hobby, 65 | @RequestParam(value = "active", required = false) Integer active) { 66 | logger.info("save Student..."); 67 | System.out.println(active); 68 | System.out.println(createTime); 69 | studentRepository.save(new Student(id, name, number, score,createTime,hobby,active)); 70 | } 71 | @RequestMapping(value = "/studentinfo", method = {RequestMethod.PATCH }, produces = MediaType.APPLICATION_JSON_VALUE) 72 | public void modifyStudent(@RequestParam(value = "id", required = false) String id, 73 | @RequestParam(value = "name", required = false) String name, 74 | @RequestParam(value = "number", required = false) String number, 75 | @RequestParam(value = "score", required = false) Double score, 76 | @RequestParam(value = "createTime", required = false) Date createTime, 77 | @RequestParam(value = "hobby", required = false) String hobby, 78 | @RequestParam(value = "active", required = false) Integer active) { 79 | logger.info("update Student..."); 80 | Student stu = studentRepository.findOne(id); 81 | stu.setName(name); 82 | stu.setNumber(number); 83 | stu.setScore(score); 84 | stu.setCreateTime(createTime); 85 | stu.setHobby(hobby); 86 | stu.setActive(active); 87 | studentRepository.save(stu); 88 | } 89 | 90 | @RequestMapping(value = "/studentinfo/{id}", method = {RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE) 91 | public void deleteStudent(@PathVariable("id") String id) { 92 | logger.info("delete Student..."); 93 | if(StringUtils.isNotBlank(id)) { 94 | studentRepository.delete(id); 95 | } 96 | } 97 | @RequestMapping(value = "/studentinfo", method = {RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE) 98 | public void deleteStudents(@RequestParam(value="ids",required=true) String[] ids) { 99 | logger.info("delete Students..."); 100 | for (String id : ids) { 101 | studentRepository.delete(id); 102 | } 103 | } 104 | 105 | @InitBinder 106 | protected void initBinder(WebDataBinder binder) { 107 | try { 108 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 109 | binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 110 | } catch (IllegalArgumentException e) { 111 | e.printStackTrace(); 112 | }catch (Exception e) { 113 | e.printStackTrace(); 114 | } 115 | } 116 | 117 | @RequestMapping(value="/changeColor", method= {RequestMethod.POST,RequestMethod.GET}) 118 | public void changeColor(@RequestParam("color") String color) { 119 | color = StringUtils.isBlank(color)?"#cb39f9":color; 120 | StringBuffer sb = new StringBuffer(); 121 | sb.append("$themeColor: "+color+" !default;\r\n"); 122 | sb.append("$--color-primary: $themeColor;\r\n"); 123 | sb.append("$--font-path: '../node_modules/element-ui/lib/theme-chalk/fonts';\r\n"); 124 | sb.append("@import \"../node_modules/element-ui/packages/theme-chalk/src/index\";"); 125 | 126 | write2File("E:\\dev\\IntellijSpace\\vue-irp\\src\\element-variables.scss", sb.toString()); 127 | write2File("E:/dev/IntellijSpace/vue-irp/src/theme-default.scss", color); 128 | System.err.println("changeColor finished: " + color); 129 | } 130 | 131 | @RequestMapping(value = "/defaultTheme", method = { RequestMethod.POST, RequestMethod.GET }) 132 | public Map themeDefault() { 133 | // 创建文件对象 134 | File fileText = new File("E:/dev/IntellijSpace/vue-irp/src/theme-default.scss"); 135 | // 向文件写入对象写入信息 136 | BufferedReader breader=null; 137 | FileReader fileReader = null; 138 | String readLine=null; 139 | try { 140 | fileReader = new FileReader(fileText); 141 | breader = new BufferedReader(fileReader); 142 | readLine = breader.readLine(); 143 | // while(true){ 144 | // readLine = breader.readLine(); 145 | // if(readLine == null){ 146 | // break; 147 | // } 148 | // System.out.println(readLine); 149 | // } 150 | System.err.println(readLine); 151 | 152 | } catch (IOException e) { 153 | e.printStackTrace(); 154 | }finally { 155 | 156 | if(null != fileReader) { 157 | try { 158 | fileReader.close(); 159 | } catch (IOException e) { 160 | e.printStackTrace(); 161 | } 162 | } 163 | if(null != breader) { 164 | try { 165 | breader.close(); 166 | } catch (IOException e) { 167 | e.printStackTrace(); 168 | } 169 | } 170 | } 171 | Map map = new HashMap<>(); 172 | map.put("color", readLine==null?"#cb39f9":readLine); 173 | return map; 174 | 175 | } 176 | 177 | public void write2File(final String strFilename, final String strBuffer) { 178 | try { 179 | // 创建文件对象 180 | File fileText = new File(strFilename); 181 | // 向文件写入对象写入信息 182 | FileWriter fileWriter = new FileWriter(fileText); 183 | 184 | // 写文件 185 | fileWriter.write(strBuffer); 186 | // 关闭 187 | fileWriter.close(); 188 | } catch (IOException e) { 189 | // 190 | e.printStackTrace(); 191 | } 192 | } 193 | 194 | } 195 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/TestVuex.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Controller; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | import org.springframework.web.bind.annotation.RequestParam; 12 | import org.springframework.web.bind.annotation.ResponseBody; 13 | 14 | import com.example.demo.bean.User; 15 | import com.example.demo.repository.UserRepository; 16 | 17 | @Controller 18 | @RequestMapping("/api") 19 | public class TestVuex { 20 | 21 | @Autowired 22 | private UserRepository userRepository; 23 | 24 | @ResponseBody 25 | @RequestMapping(value = "/getUsers", method = { RequestMethod.GET, RequestMethod.POST }) 26 | public Map testVuex(@RequestParam("value") Integer value) { 27 | System.out.println(value); 28 | Map map = new HashMap<>(); 29 | map.put("code", "200"); 30 | List list = userRepository.findAll(); 31 | map.put("result", list); 32 | return map; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/TreeNodeController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.ResponseBody; 9 | 10 | import com.example.demo.bean.TreeNode; 11 | import com.example.demo.repository.TreeNodeRepository; 12 | 13 | @Controller 14 | @RequestMapping(value="/api") 15 | public class TreeNodeController { 16 | 17 | @Autowired 18 | private TreeNodeRepository treeNodeRepository; 19 | 20 | 21 | @RequestMapping(value="/loadTree") 22 | @ResponseBody 23 | public List loadTree() { 24 | // List treeNodeList = treeNodeRepository.findAll(); 25 | // return treeNodeList; 26 | return null; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.controller; 2 | 3 | import java.util.Date; 4 | import java.util.HashMap; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.data.domain.Page; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RequestMethod; 15 | import org.springframework.web.bind.annotation.RequestParam; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | import com.example.demo.bean.User; 19 | import com.example.demo.repository.UserRepository; 20 | 21 | @RestController 22 | public class UserController extends BaseController { 23 | private static final Logger logger = LoggerFactory.getLogger(UserController.class); 24 | @Autowired 25 | private UserRepository userRepository; 26 | 27 | /** 28 | * 可以启动多个server在不同的端口, nginx 作为负载均衡 29 | * 30 | * 正向代理: 即所谓的代理, 例如google.com 无法访问,可以通过代理服务器来访问谷歌网站的代理即为正向代理 31 | * 反向代理:用户访问一个站点,例如http://www.abc.com/readme.md , 但是 www.abc.com 跟没有readme.md对应的资源, 32 | * 那么这个服务器就去请求别的网站获取readme.md 这个资源的行为叫做反向代理 33 | * 34 | */ 35 | @Value("${server.port}") 36 | private int port; 37 | 38 | @RequestMapping(value= {"/","/index"}) 39 | public String index() { 40 | logger.info("visite port is {}",port); 41 | return "nginx come to server backend :"+ port; 42 | } 43 | 44 | @SuppressWarnings("serial") 45 | @RequestMapping(value = "/userinfo", method = { RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) 46 | public Page getUsers(@RequestParam(value = "page", required = false) Integer page, 47 | @RequestParam(value = "per_page", required = false) Integer perPage, 48 | @RequestParam("name") final String name, 49 | @RequestParam("phone") final String phone, 50 | @RequestParam("username") final String username, 51 | @RequestParam("sorts") String sortType) { 52 | return queryPagination(page, perPage, sortType, new HashMap() {{ 53 | put("name", name); 54 | put("phone", phone); 55 | put("username", username); 56 | }},UserRepository.class); 57 | 58 | } 59 | 60 | @RequestMapping(value = "/userinfo", method = {RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE) 61 | public void saveUser( 62 | @RequestParam(value = "checkpass",required=false) final String checkpass, 63 | @RequestParam(value="email",required=false) final String email, 64 | @RequestParam(value="id",required=false) final String id, 65 | @RequestParam(value="is_active",required=false) final boolean is_active, 66 | @RequestParam(value="name",required=false) final String name, 67 | @RequestParam("phone") final String phone, 68 | @RequestParam("username") final String username, 69 | @RequestParam("password") final String password, 70 | @RequestParam(value="create_time",required=false) Date create_time ) { 71 | logger.info("save user..."); 72 | if(null == create_time) { 73 | create_time = new Date(); 74 | } 75 | User user = new User(id, username, username, phone, email, create_time, is_active, checkpass); 76 | userRepository.save(user); 77 | } 78 | @RequestMapping(value = "/userinfo", method = {RequestMethod.PATCH }, produces = MediaType.APPLICATION_JSON_VALUE) 79 | public void updateUser( 80 | @RequestParam(value = "checkpass",required=false) final String checkpass, 81 | @RequestParam(value="email",required=false) final String email, 82 | @RequestParam(value="id",required=false) final String id, 83 | @RequestParam(value="is_active",required=false) final boolean is_active, 84 | @RequestParam(value="name",required=false) final String name, 85 | @RequestParam(value="phone",required=false) final String phone, 86 | @RequestParam(value="username",required=false) final String username, 87 | @RequestParam(value="password",required=false) final String password, 88 | @RequestParam(value="create_time",required=false) final Date create_time ) { 89 | logger.info("update user..."); 90 | User user = userRepository.findOne(id); 91 | user.setName(name); 92 | user.setPhone(phone); 93 | user.setEmail(email); 94 | userRepository.save(user); 95 | } 96 | @RequestMapping(value = "/userinfo/{id}", method = {RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE) 97 | public void delete(@PathVariable("id") final String id) { 98 | logger.info("delete user..."); 99 | userRepository.delete(id); 100 | } 101 | @RequestMapping(value = "/userinfo", method = {RequestMethod.DELETE }, produces = MediaType.APPLICATION_JSON_VALUE) 102 | public void delete2(@RequestParam("ids") final String[] ids) { 103 | logger.info("批量删除 user..."); 104 | System.out.println(ids.length); 105 | for (String id : ids) { 106 | userRepository.delete(id); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/filter/FilterDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.annotation.WebFilter; 12 | 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.core.Ordered; 16 | import org.springframework.core.annotation.Order; 17 | 18 | 19 | @Order(value = Ordered.HIGHEST_PRECEDENCE) 20 | @WebFilter(urlPatterns = "/*", filterName = "apiFilter") 21 | public class FilterDemo implements Filter { 22 | private static final Logger logger = LoggerFactory.getLogger(FilterDemo.class); 23 | 24 | @Override 25 | public void init(FilterConfig filterConfig) throws ServletException { 26 | System.err.println("过滤器FilterDemo初始化"); 27 | logger.info("我是过滤器"); 28 | 29 | } 30 | 31 | @Override 32 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 33 | throws IOException, ServletException { 34 | System.err.println("1.经过过滤器"); 35 | chain.doFilter(request, response); 36 | } 37 | 38 | @Override 39 | public void destroy() { 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/interceptor/InterceptorDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.interceptor; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.servlet.HandlerInterceptor; 9 | import org.springframework.web.servlet.ModelAndView; 10 | 11 | public class InterceptorDemo implements HandlerInterceptor { 12 | private static final Logger logger = LoggerFactory.getLogger(InterceptorDemo.class); 13 | 14 | @Override 15 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 16 | logger.info("InterceptorDemo"); 17 | System.err.println("2.我是拦截器,拦截的url:/api/**"); 18 | return true; 19 | } 20 | 21 | @Override 22 | public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 23 | ModelAndView modelAndView) throws Exception { 24 | 25 | } 26 | 27 | @Override 28 | public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 29 | throws Exception { 30 | // TODO Auto-generated method stub 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/Barchart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.RenderingHints; 6 | import java.text.DecimalFormat; 7 | 8 | import org.jfree.chart.ChartFactory; 9 | import org.jfree.chart.JFreeChart; 10 | import org.jfree.chart.axis.CategoryAxis; 11 | import org.jfree.chart.axis.NumberAxis; 12 | import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; 13 | import org.jfree.chart.plot.CategoryPlot; 14 | import org.jfree.chart.plot.PlotOrientation; 15 | import org.jfree.chart.renderer.category.BarRenderer; 16 | import org.jfree.chart.renderer.category.StackedBarRenderer; 17 | import org.jfree.data.category.CategoryDataset; 18 | import org.jfree.data.category.DefaultCategoryDataset; 19 | 20 | /** 21 | * 柱状图 22 | * 23 | * @author huozhicheng@gmail.com 24 | * @date 2013-1-8下午2:15:14 25 | * @version 1.0 26 | */ 27 | public class Barchart { 28 | 29 | /** 30 | * 创建柱状图 31 | * @param chartTitle 图表标题 32 | * @param xName x轴标题 33 | * @param yName y轴标题 34 | * @param dataset 数据集 35 | * @return 36 | */ 37 | public static JFreeChart createChart(String chartTitle, String xName,String yName, CategoryDataset dataset) { 38 | /* 39 | * createBarChart的参数分别为: 40 | * 标题,横坐标标题,纵坐标标题,数据集,图标方向(水平、垂直),是否显示图例,是否显示tooltips,是否urls 41 | */ 42 | JFreeChart chart = ChartFactory.createBarChart(chartTitle, xName, yName, 43 | dataset, PlotOrientation.VERTICAL, true, true, false); 44 | /* 45 | * VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭, 46 | * 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看 47 | */ 48 | chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING, 49 | RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); 50 | // 背景色 51 | chart.setBackgroundPaint(Color.white); 52 | // 设置标题字体 53 | chart.getTitle().setFont(new Font("宋体", Font.BOLD, 14)); 54 | // 图例背景色 55 | chart.getLegend().setBackgroundPaint(new Color(110, 182, 229)); 56 | // 图例字体 57 | chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); 58 | 59 | CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot(); 60 | // 设置纵虚线可见 61 | //categoryPlot.setDomainGridlinesVisible(true); 62 | // 虚线色彩 63 | //categoryPlot.setDomainGridlinePaint(Color.black); 64 | // 设置横虚线可见 65 | categoryPlot.setRangeGridlinesVisible(true); 66 | // 虚线色彩 67 | categoryPlot.setRangeGridlinePaint(Color.black); 68 | // 设置柱的透明度 69 | categoryPlot.setForegroundAlpha(1.0f); 70 | // 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确) 71 | categoryPlot.setBackgroundPaint(new Color(110, 182, 229)); 72 | 73 | /* 74 | * categoryPlot.setRangeCrosshairVisible(true); 75 | * categoryPlot.setRangeCrosshairPaint(Color.blue); 76 | */ 77 | 78 | // 纵坐标--范围轴 79 | NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis(); 80 | // 纵坐标y轴坐标字体 81 | numberAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12)); 82 | // 纵坐标y轴标题字体 83 | numberAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12)); 84 | // 设置最高的一个 Item 与图片顶端的距离 85 | // numberAxis.setUpperMargin(0.5); 86 | // 设置最低的一个 Item 与图片底端的距离 87 | // numberAxis.setLowerMargin(0.5); 88 | // 设置刻度单位 为Integer 89 | numberAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 90 | 91 | // 横坐标--类别轴、域 92 | CategoryAxis categoryAxis = categoryPlot.getDomainAxis(); 93 | // 横坐标x轴坐标字体 94 | categoryAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12)); 95 | // 横坐标x轴标题字体 96 | categoryAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12)); 97 | // 类别轴的位置,倾斜度 98 | // categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(0.5235987755982988D)); 99 | // categoryAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 100 | // 是否完整显示 101 | // 设置距离图片左端距离 102 | categoryAxis.setLowerMargin(0.1D); 103 | // 设置距离图片右端距离 104 | categoryAxis.setUpperMargin(0.1D); 105 | 106 | // 渲染 - 中间的部分 107 | BarRenderer barRenderer = (BarRenderer) categoryPlot.getRenderer(); 108 | // 设置柱子宽度 109 | barRenderer.setMaximumBarWidth(0.05); 110 | // 设置柱子高度 111 | barRenderer.setMinimumBarLength(0.2); 112 | // 设置柱子边框颜色 113 | barRenderer.setBaseOutlinePaint(Color.BLACK); 114 | // 设置柱子边框可见 115 | barRenderer.setDrawBarOutline(true); 116 | // 设置柱的颜色 117 | barRenderer.setSeriesPaint(0, new Color(0, 255, 0)); 118 | barRenderer.setSeriesPaint(1, new Color(0, 0, 255)); 119 | barRenderer.setSeriesPaint(2, new Color(255, 0, 0)); 120 | // 设置每个柱之间距离 121 | barRenderer.setItemMargin(0.2D); 122 | // 显示每个柱的数值,并修改该数值的字体属性 123 | barRenderer.setIncludeBaseInRange(true); 124 | barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 125 | barRenderer.setBaseItemLabelsVisible(true); 126 | 127 | return chart; 128 | } 129 | 130 | /** 131 | * 柱状图数据集 132 | * 133 | * @return 134 | */ 135 | public static CategoryDataset createDataset() { 136 | String str1 = "Java EE开发"; 137 | String str2 = "IOS开发"; 138 | String str3 = "Android开发"; 139 | String str4 = "1月"; 140 | String str5 = "2月"; 141 | String str6 = "3月"; 142 | String str7 = "4月"; 143 | String str8 = "5月"; 144 | 145 | DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 146 | 147 | dataset.addValue(1.0D, str1, str4); 148 | dataset.addValue(4.0D, str1, str5); 149 | dataset.addValue(3.0D, str1, str6); 150 | dataset.addValue(5.0D, str1, str7); 151 | dataset.addValue(5.0D, str1, str8); 152 | 153 | dataset.addValue(5.0D, str2, str4); 154 | dataset.addValue(7.0D, str2, str5); 155 | dataset.addValue(6.0D, str2, str6); 156 | dataset.addValue(8.0D, str2, str7); 157 | dataset.addValue(4.0D, str2, str8); 158 | 159 | dataset.addValue(4.0D, str3, str4); 160 | dataset.addValue(3.0D, str3, str5); 161 | dataset.addValue(2.0D, str3, str6); 162 | dataset.addValue(3.0D, str3, str7); 163 | dataset.addValue(6.0D, str3, str8); 164 | return dataset; 165 | } 166 | 167 | /** 168 | * 生成堆栈柱状图 169 | * @param chartTitle 图表标题 170 | * @param xName x轴名称 171 | * @param yName y轴名称 172 | * @param dataset 数据集 173 | * @return 174 | */ 175 | public static JFreeChart createStackedBarChart(String chartTitle, String xName,String yName, CategoryDataset dataset) { 176 | 177 | //JFreeChart对象 178 | JFreeChart chart = ChartFactory.createStackedBarChart( 179 | chartTitle, //图表标题 180 | xName, //目录轴的显示标签 181 | yName, //数值轴的显示标签 182 | dataset, //数据集 183 | PlotOrientation.VERTICAL, //图表方向:水平、垂直 184 | true, //是否显示图例 185 | false, //是否生成工具 186 | false //是否生成URL链接 187 | ); 188 | //图例字体清晰 189 | chart.setTextAntiAlias(false); 190 | //图表背景色 191 | chart.setBackgroundPaint(Color.WHITE); 192 | //建立图表标题字体 193 | Font titleFont = new Font("宋体", Font.BOLD, 14); 194 | //建立图表图例字体 195 | Font legendFont = new Font("宋体", Font.PLAIN, 12); 196 | //建立x,y轴坐标的字体 197 | Font axisFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); 198 | //设置图表的标题字体 199 | chart.getTitle().setFont(titleFont); 200 | //设置图表的图例字体 201 | chart.getLegend().setItemFont(legendFont); 202 | 203 | //Plot对象是图形的绘制结构对象 204 | CategoryPlot plot = chart.getCategoryPlot(); 205 | 206 | //设置横虚线可见 207 | plot.setRangeGridlinesVisible(true); 208 | //虚线色彩 209 | plot.setRangeGridlinePaint(Color.black); 210 | //设置柱的透明度(如果是3D的必须设置才能达到立体效果,如果是2D的设置则使颜色变淡) 211 | //plot.setForegroundAlpha(0.65f); 212 | 213 | /** ---------- RangeAxis (范围轴,相当于 y 轴)---------- **/ 214 | //数据轴精度 215 | NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis(); 216 | numberAxis.setLabelFont(axisFont);//轴标题字体 217 | numberAxis.setTickLabelFont(axisFont);//轴数值字体 218 | //设置最高的一个 Item 与图片顶端的距离 219 | numberAxis.setUpperMargin(0.15); 220 | //设置最低的一个 Item 与图片底端的距离 221 | numberAxis.setLowerMargin(0.15); 222 | //设置最大值是1 223 | numberAxis.setUpperBound(1); 224 | //设置数据轴坐标从0开始 225 | //numberAxis.setAutoRangeIncludesZero(true); 226 | //数据显示格式是百分比 227 | DecimalFormat df = new DecimalFormat("0.00%"); 228 | //数据轴数据标签的显示格式 229 | numberAxis.setNumberFormatOverride(df); 230 | 231 | /** ---------- DomainAxis (区域轴,相当于 x 轴)---------- **/ 232 | CategoryAxis domainAxis = (CategoryAxis)plot.getDomainAxis(); 233 | domainAxis.setLabelFont(axisFont);//轴标题字体 234 | domainAxis.setTickLabelFont(axisFont);//轴数值字体 235 | 236 | // x轴坐标太长,建议设置倾斜,如下两种方式选其一,两种效果相同 237 | // 倾斜(1)横轴上的 Lable 45度倾斜 238 | // domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); 239 | // 倾斜(2)Lable(Math.PI 3.0)度倾斜 240 | // domainAxis.setCategoryLabelPositions(CategoryLabelPositions 241 | // .createUpRotationLabelPositions(Math.PI / 3.0)); 242 | 243 | //横轴上的 Lable 是否完整显示 244 | domainAxis.setMaximumCategoryLabelWidthRatio(1f); 245 | 246 | /** ---------- Renderer (图形绘制单元)---------- **/ 247 | //Renderer 对象是图形的绘制单元 248 | StackedBarRenderer renderer = new StackedBarRenderer(); 249 | //设置柱子宽度 250 | renderer.setMaximumBarWidth(0.05D); 251 | //设置柱子高度 252 | renderer.setMinimumBarLength(0.1D); 253 | //设置柱的边框颜色 254 | renderer.setBaseOutlinePaint(Color.BLACK); 255 | //设置柱的边框可见 256 | renderer.setDrawBarOutline(true); 257 | //设置柱的颜色(可设定也可默认) 258 | renderer.setSeriesPaint(0, new Color(0, 255, 0)); 259 | renderer.setSeriesPaint(1, new Color(0, 0, 255)); 260 | //设置每个平行柱的之间距离 261 | renderer.setItemMargin(0.4); 262 | 263 | // 显示每个柱的数值,并修改该数值的字体属性 264 | renderer.setIncludeBaseInRange(true); 265 | renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 266 | renderer.setBaseItemLabelsVisible(true); 267 | 268 | plot.setRenderer(renderer); 269 | 270 | return chart; 271 | } 272 | } 273 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/ChartServlet.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.ServletException; 6 | import javax.servlet.http.HttpServlet; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import org.jfree.chart.JFreeChart; 11 | import org.jfree.chart.servlet.ServletUtilities; 12 | import org.jfree.data.category.CategoryDataset; 13 | import org.jfree.data.general.DatasetUtilities; 14 | 15 | /** 16 | * JFreeChart Servlet 17 | * @author huozhicheng@gmail.com 18 | * @date 2013-1-10下午5:34:22 19 | * @version 1.0 20 | */ 21 | public class ChartServlet extends HttpServlet{ 22 | 23 | private static final long serialVersionUID = -3066626067997142035L; 24 | 25 | @Override 26 | protected void service(HttpServletRequest request, HttpServletResponse response) 27 | throws ServletException, IOException { 28 | JFreeChart chart = null; 29 | if(request.getParameter("type").equals("barchart")){ 30 | chart = Barchart.createChart("公司招聘人数","月份","人数",Barchart.createDataset()); 31 | }else if(request.getParameter("type").equals("piechart")){ 32 | double[] data = 33 | { 9, 91 }; 34 | String[] keys = 35 | { "失败率", "成功率" }; 36 | chart = Piechart.createPieChart3D("饼状图",Piechart.getDataPieSetByUtil(data, keys),keys); 37 | }else if(request.getParameter("type").equals("linechart")){ 38 | double[][] data = new double[][] 39 | { 40 | { 672, 766, 223, 540, 126 }, 41 | { 325, 521, 210, 340, 106 }, 42 | { 332, 256, 523, 240, 526 } }; 43 | String[] rowKeys = 44 | { "苹果", "梨子", "葡萄" }; 45 | String[] columnKeys = 46 | { "北京", "上海", "广州", "成都", "深圳" }; 47 | CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); 48 | chart = LineChart.createLineChart("折线图", "x轴", "y轴", dataset); 49 | }else if(request.getParameter("type").equals("stackedbarchart")){ 50 | double[][] data = new double[][] 51 | { 52 | { 0.21, 0.66, 0.23, 0.40, 0.26 }, 53 | { 0.25, 0.21, 0.10, 0.40, 0.16 } }; 54 | String[] rowKeys = { "苹果", "梨子" }; 55 | String[] columnKeys = { "北京", "上海", "广州", "成都", "深圳" }; 56 | 57 | CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); 58 | chart = Barchart.createStackedBarChart("柱状图", "x坐标", "y坐标", dataset); 59 | } 60 | //ServletUtilities是面向web开发的工具类,返回一个字符串文件名,文件名自动生成,生成好的图片会自动放在服务器(tomcat)的临时文件下(temp) 61 | String filename = ServletUtilities.saveChartAsPNG(chart, 800, 400, null, request.getSession()); 62 | //根据文件名去临时目录下寻找该图片,这里的/DisplayChart路径要与配置文件里用户自定义的一致 63 | String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename; 64 | request.setAttribute("imgurl", graphURL); 65 | request.getRequestDispatcher("index.jsp").forward(request, response); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/CreateJFreeChart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | import java.awt.Color; 3 | import java.awt.Font; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | 7 | import org.jfree.chart.ChartFactory; 8 | import org.jfree.chart.ChartUtilities; 9 | import org.jfree.chart.JFreeChart; 10 | import org.jfree.chart.axis.CategoryAxis; 11 | import org.jfree.chart.axis.CategoryLabelPositions; 12 | import org.jfree.chart.axis.NumberAxis; 13 | import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; 14 | import org.jfree.chart.plot.CategoryPlot; 15 | import org.jfree.chart.plot.PlotOrientation; 16 | import org.jfree.chart.renderer.category.LineAndShapeRenderer; 17 | import org.jfree.data.category.CategoryDataset; 18 | import org.jfree.data.general.DatasetUtilities; 19 | 20 | public class CreateJFreeChart { 21 | 22 | /** 23 | * 生成折线图 24 | * @param chartTitle 图片标题 25 | * @param xTitle x轴标题 26 | * @param yTitle y轴标题 27 | * @param xyDataset 数据集 28 | */ 29 | public JFreeChart makeLineAndShapeChart(String chartTitle, String xTitle, String yTitle, CategoryDataset xyDataset){ 30 | //构建一个chart 31 | JFreeChart chart = ChartFactory.createLineChart(chartTitle, xTitle, yTitle, xyDataset, PlotOrientation.VERTICAL, true, true, false); 32 | chart.setTextAntiAlias(false); 33 | //设置背景颜色 34 | chart.setBackgroundPaint(Color.WHITE); 35 | //配置字体 36 | Font xfont = new Font("宋体",Font.TRUETYPE_FONT,12) ;// X轴字体 37 | Font yfont = new Font("SansSerif",Font.TRUETYPE_FONT,12) ;// Y轴字体 38 | Font legendFont = new Font("宋体",Font.PLAIN,12) ;//图例标题字体 39 | Font titleFont = new Font("隶书", Font.BOLD , 25) ; // 图片标题 40 | 41 | //设置图标题title的字体 42 | chart.getTitle().setFont(titleFont); 43 | 44 | //设置图例的字体 45 | chart.getLegend().setItemFont(legendFont); 46 | //RectangleEdge rectangleEdge = new RectangleEdge("adf"); 47 | 48 | //chart.getLegend().setPosition(position); 49 | 50 | 51 | //图形的绘制结构对象 52 | CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); 53 | // x轴 分类轴网格是否可见 54 | categoryplot.setDomainGridlinesVisible(true); 55 | // y轴 数据轴网格是否可见 56 | categoryplot.setRangeGridlinesVisible(true); 57 | // 虚线色彩 58 | categoryplot.setRangeGridlinePaint(Color.WHITE); 59 | // 虚线色彩 60 | categoryplot.setDomainGridlinePaint(Color.WHITE); 61 | //折线图的背景颜色 62 | categoryplot.setBackgroundPaint(Color.lightGray); 63 | // 设置轴和面板之间的距离 64 | //categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); 65 | 66 | /********************** 横轴 x *****************/ 67 | CategoryAxis domainAxis = categoryplot.getDomainAxis(); 68 | domainAxis.setLabelFont(xfont);// 轴标题 69 | domainAxis.setTickLabelFont(xfont);// 轴数值 70 | //domainAxis.setLabelPaint(Color.BLUE);//轴标题的颜色 71 | //domainAxis.setTickLabelPaint(Color.BLUE);//轴数值的颜色 72 | 73 | //横轴 lable 的位置 横轴上的 Lable 45度倾斜 DOWN_45 74 | domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); 75 | // 设置距离图片左端距离 76 | domainAxis.setLowerMargin(0.0); 77 | // 设置距离图片右端距离 78 | domainAxis.setUpperMargin(0.0); 79 | 80 | /********************** 纵轴 y *****************/ 81 | NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();//ValueAxis 82 | numberaxis.setLabelFont(yfont); 83 | numberaxis.setTickLabelFont(yfont); 84 | numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 85 | numberaxis.setAutoRangeIncludesZero(true); 86 | 87 | // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!! 88 | LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot.getRenderer(); 89 | lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见 90 | lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见 91 | 92 | // 显示折点数据 93 | lineandshaperenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 94 | lineandshaperenderer.setBaseItemLabelsVisible(true); 95 | 96 | return chart; 97 | } 98 | public static void main(String args[]){ 99 | double [][] data = new double[][]{{533,214,614,542,724},{462,836,345,854,224},{245,614,751,332,456}}; 100 | String[] rowKeys = {"宝马","奔驰","大众"}; 101 | String[] columnKeys = {"北京", "上海", "广州", "成都", "深圳"}; 102 | CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); 103 | try { 104 | FileOutputStream fos = new FileOutputStream("e:/test/abc.png"); 105 | ChartUtilities.writeChartAsPNG(fos, new CreateJFreeChart().makeLineAndShapeChart("各地汽车销量", "城市", "销量", dataset), 800, 600); 106 | } catch (IOException e) { 107 | // TODO Auto-generated catch block 108 | e.printStackTrace(); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/CustomLegendTitle.java: -------------------------------------------------------------------------------- 1 | //package com.example.demo.jfreechart; 2 | // 3 | //import java.awt.BasicStroke; 4 | //import java.awt.Font; 5 | //import java.awt.Paint; 6 | //import java.awt.Rectangle; 7 | // 8 | //import org.jfree.chart.LegendItem; 9 | //import org.jfree.chart.LegendItemSource; 10 | //import org.jfree.chart.block.Block; 11 | //import org.jfree.chart.block.BlockContainer; 12 | //import org.jfree.chart.block.BorderArrangement; 13 | //import org.jfree.chart.block.CenterArrangement; 14 | //import org.jfree.chart.block.LabelBlock; 15 | //import org.jfree.chart.title.LegendGraphic; 16 | //import org.jfree.chart.title.LegendItemBlockContainer; 17 | //import org.jfree.chart.title.LegendTitle; 18 | // 19 | //public class CustomLegendTitle extends LegendTitle { 20 | // /** 21 | // * 22 | // */ 23 | // private static final long serialVersionUID = -5017893068151590925L; 24 | // 25 | // legendItemGraphicPadding; 26 | // 27 | // public CustomLegendTitle(LegendItemSource source) { 28 | // super(source); 29 | // } 30 | // 31 | // @Override 32 | // public Block createLegendItemBlock(LegendItem item) { 33 | // BlockContainer result; 34 | // // LegendGraphic lg = new LegendGraphic(item.getShape(), item.getFillPaint()); 35 | // LegendGraphic lg = new LegendGraphic(item.getShape(), item.getFillPaint()); 36 | // lg.setFillPaintTransformer(item.getFillPaintTransformer()); 37 | // lg.setShapeFilled(item.isShapeFilled()); 38 | // lg.setLine(item.getLine()); 39 | // lg.setLine(new Rectangle(6, 4)); 40 | // lg.setLineStroke(new BasicStroke(4f)); 41 | // lg.setLinePaint(item.getLinePaint()); 42 | // lg.setLineVisible(item.isLineVisible()); 43 | // lg.setShapeVisible(item.isShapeVisible()); 44 | // lg.setShapeOutlineVisible(item.isShapeOutlineVisible()); 45 | // lg.setOutlinePaint(item.getOutlinePaint()); 46 | // lg.setOutlineStroke(item.getOutlineStroke()); 47 | // lg.setPadding(this.legendItemGraphicPadding); 48 | // LegendItemBlockContainer legendItem = new LegendItemBlockContainer(new BorderArrangement(), item.getDataset(), 49 | // item.getSeriesKey()); 50 | // lg.setShapeAnchor(getLegendItemGraphicAnchor()); 51 | // lg.setShapeLocation(getLegendItemGraphicLocation()); 52 | // legendItem.add(lg, this.legendItemGraphicEdge); 53 | // Font textFont = item.getLabelFont(); 54 | // if (textFont == null) { 55 | // textFont = this.itemFont; 56 | // } 57 | // Paint textPaint = item.getLabelPaint(); 58 | // if (textPaint == null) { 59 | // textPaint = this.itemPaint; 60 | // } 61 | // LabelBlock labelBlock = new LabelBlock(item.getLabel(), textFont, textPaint); 62 | // labelBlock.setPadding(this.itemLabelPadding); 63 | // legendItem.add(labelBlock); 64 | // legendItem.setToolTipText(item.getToolTipText()); 65 | // legendItem.setURLText(item.getURLText()); 66 | // result = new BlockContainer(new CenterArrangement()); 67 | // result.add(legendItem); 68 | // return result; 69 | // } 70 | //} 71 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/JFreeChartDemoCombined.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.BasicStroke; 4 | import java.awt.Color; 5 | import java.awt.Font; 6 | import java.io.File; 7 | import java.io.FileOutputStream; 8 | import java.text.SimpleDateFormat; 9 | 10 | import org.jfree.chart.ChartColor; 11 | import org.jfree.chart.ChartFactory; 12 | import org.jfree.chart.ChartUtilities; 13 | import org.jfree.chart.JFreeChart; 14 | import org.jfree.chart.axis.CategoryAxis; 15 | import org.jfree.chart.axis.CategoryLabelPositions; 16 | import org.jfree.chart.axis.DateAxis; 17 | import org.jfree.chart.axis.NumberAxis; 18 | import org.jfree.chart.axis.ValueAxis; 19 | import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; 20 | import org.jfree.chart.plot.CategoryPlot; 21 | import org.jfree.chart.plot.PlotOrientation; 22 | import org.jfree.chart.plot.XYPlot; 23 | import org.jfree.chart.renderer.category.LineAndShapeRenderer; 24 | import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; 25 | import org.jfree.chart.title.TextTitle; 26 | import org.jfree.data.category.CategoryDataset; 27 | import org.jfree.data.general.SeriesException; 28 | import org.jfree.data.time.Second; 29 | import org.jfree.data.time.TimeSeries; 30 | import org.jfree.data.time.TimeSeriesCollection; 31 | import org.jfree.data.xy.XYDataset; 32 | 33 | public class JFreeChartDemoCombined { 34 | 35 | private static final String CHART_PATH = "E:\\file\\JFreeChart\\demo\\"; 36 | 37 | public static void main(String[] args) { 38 | JFreeChartDemoCombined pm = new JFreeChartDemoCombined(); 39 | // 生成时序图 40 | pm.makeTimeSeriesChart(); 41 | 42 | System.err.println("Jfree Chart Run Over..."); 43 | } 44 | 45 | @SuppressWarnings("deprecation") 46 | public void makeTimeSeriesChart() { 47 | 48 | final XYDataset dataset = timeSeriesDataSet(); 49 | final XYDataset timeSeriesTwo = timeSeriesDataSet2(); 50 | JFreeChart chart = ChartFactory.createTimeSeriesChart("时序图", "秒", "值", dataset, true, true, false); 51 | XYPlot plot = chart.getXYPlot(); 52 | /** 53 | // 解决乱码问题 54 | // 1. 图形标题文字设置 55 | TextTitle textTitle = chart.getTitle(); 56 | textTitle.setFont(new Font("宋体", Font.BOLD, 20)); 57 | 58 | // 2. 图形X轴坐标文字的设置 59 | XYPlot plot = chart.getXYPlot(); 60 | ValueAxis axis = plot.getDomainAxis(); 61 | axis.setLabelFont(new Font("宋体", Font.BOLD, 22)); // 设置X轴坐标上标题的文字 62 | axis.setTickLabelFont(new Font("宋体", Font.BOLD, 15)); // 设置X轴坐标上的文字 63 | 64 | // 2. 图形Y轴坐标文字的设置 65 | ValueAxis valueAxis = plot.getRangeAxis(); 66 | valueAxis.setLabelFont(new Font("宋体", Font.BOLD, 15)); // 设置Y轴坐标上标题的文字 67 | valueAxis.setTickLabelFont(new Font("sans-serif", Font.BOLD, 12));// 设置Y轴坐标上的文字 68 | */ 69 | // 设置总的背景颜色 70 | chart.setBackgroundPaint(ChartColor.WHITE); 71 | // 设置标题颜色 72 | chart.getTitle().setPaint(ChartColor.blue); 73 | // 获得图表对象 74 | // CategoryPlot p = chart.getCategoryPlot(); 75 | // 设置图的背景颜色 76 | plot.setBackgroundPaint(ChartColor.WHITE); 77 | 78 | // 设置表格线颜色 79 | // p.setRangeGridlinePaint(ChartColor.red); 80 | 81 | 82 | /**添加折线图*/ 83 | NumberAxis numberAxis = new NumberAxis("时序图横轴"); 84 | numberAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); 85 | plot.setRangeAxis(1, numberAxis);// 设置该新轴对应索引 86 | plot.setDataset(0, dataset);// 设置数据集索引 87 | plot.setDataset(1, timeSeriesTwo);// 设置数据集索引 88 | plot.mapDatasetToRangeAxis(1, 1);// 将该索引映射到axis 89 | 90 | 91 | // XYBarRenderer xyBarRender = new XYBarRenderer(); 92 | // xyBarRender.setMargin(0.7); 93 | // 94 | // xyBarRender.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_LEFT)); 95 | // xyBarRender.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); 96 | // xyBarRender.setBaseItemLabelFont(new Font("Dialog", 1, 11)); 97 | // xyBarRender.setBaseToolTipGenerator(new StandardXYToolTipGenerator( 98 | // StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, 99 | // new SimpleDateFormat("yyyy-MM-dd"), new DecimalFormat( 100 | // "0.000")));// 鼠标移上去显示数据 101 | // plot.setRenderer(1, xyBarRender); 102 | 103 | 104 | TextTitle otherTitle = new TextTitle("title");// 设置副标题 105 | chart.addSubtitle(otherTitle);// 设置副标题 106 | // 设置乱码字体 107 | TextTitle textTitle = chart.getTitle(); // 设置标题字体 108 | textTitle.setFont(new Font("黑体", Font.PLAIN, 14)); 109 | chart.getLegend().setItemFont(new Font("黑体", Font.PLAIN, 14)); // 图文字体 110 | 111 | // 设置日期显示格式 112 | DateAxis axis = (DateAxis) plot.getDomainAxis(); 113 | axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM")); 114 | 115 | // XYItemRenderer render = plot.getRenderer(); 116 | // render.setBaseShapesVisible(false); 117 | // render.setBaseShapesFilled(false); 118 | 119 | // 设置墙体属性 120 | // plot.setBackgroundPaint(Color.decode("#D3D3D3")); // 设置墙体背景颜色 121 | // plot.setDomainGridlinesVisible(true); 122 | // plot.setDomainGridlinePaint(Color.black);// 虚线色彩 y轴 123 | // plot.setRangeGridlinesVisible(true); 124 | // plot.setRangeGridlinePaint(Color.black);// 虚线色彩 x轴 125 | // 对X轴做操作 126 | DateAxis domainAxis = (DateAxis) plot.getDomainAxis(); 127 | domainAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 13));// 设置X轴坐标上的文字 128 | domainAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置X轴的标题文字 129 | // domainAxis.setUpperMargin(0.05); // 设置距离图片左端距离 130 | // domainAxis.setLowerMargin(0.05); // 设置距离图片右端距离 131 | 132 | // // 对Y轴做操作 133 | // ValueAxis rAxis = plot.getRangeAxis(); 134 | // rAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 14)); // 设置Y轴坐标上的文字 135 | // rAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置Y轴的标题文字 136 | // rAxis.setUpperMargin(0.25);// 设置最高的一个 Item 与图片顶端的距离 137 | // 138 | // XYLineAndShapeRenderer lineRender = (XYLineAndShapeRenderer) plot.getRenderer(); 139 | // lineRender.setBaseShapesVisible(true); // series 点(即数据点)可见 140 | // lineRender.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见 141 | // lineRender.setBaseItemLabelsVisible(true);// 设置数据点的数据是否显示 142 | // lineandshaperenderer 143 | // .setBasePositiveItemLabelPosition(new ItemLabelPosition( 144 | // ItemLabelAnchor.INSIDE10, TextAnchor.BASELINE_LEFT)); 145 | // lineandshaperenderer 146 | // .setBaseItemLabelGenerator(new StandardXYItemLabelGenerator()); 147 | // lineandshaperenderer.setBaseItemLabelFont(new Font("Dialog", 1, 11)); 148 | // lineandshaperenderer .setBaseToolTipGenerator(new StandardXYToolTipGenerator( 149 | // StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, 150 | // new SimpleDateFormat("yyyy-MM"), new DecimalFormat( 151 | // "0.000")));// 鼠标移上去显示数据 152 | // 数据轴精度从0开始 153 | // NumberAxis na = (NumberAxis) plot.getRangeAxis(); 154 | // na.setAutoRangeIncludesZero(true); 155 | // plot.setRenderer(1, lineRender); 156 | // plot.setRenderer(1, lineRender); 157 | // lineRender.setSeriesPaint(1, Color.BLUE); // 设置第一条折现的颜色,以此类推。 158 | // lineRender.setSeriesPaint(0, Color.green); // 设置第一条折现的颜色,以此类推。 159 | // lineRender.setSeriesStroke(1, new BasicStroke(3)); 160 | // lineRender.setSeriesStroke(0, new BasicStroke(3)); 161 | // lineRender.setBaseShapesVisible(true); 162 | // lineRender.setBaseShapesFilled(true); 163 | // lineRender.setBaseLinesVisible(true); 164 | // lineRender.setLinesVisible(true); 165 | /**添加折线图*/ 166 | 167 | // 生成legend 标题 168 | // LegendTitle legendtitle = new LegendTitle(chart.getPlot()); 169 | // BlockContainer blockcontainer = new BlockContainer(new BorderArrangement()); 170 | // blockcontainer.setBorder(new BlockBorder(1.0D, 1.0D, 1.0D, 1.0D)); 171 | // BlockContainer blockcontainer1 = legendtitle.getItemContainer(); 172 | // blockcontainer1.setPadding(2D, 10D, 5D, 2D); 173 | // blockcontainer.add(blockcontainer1); 174 | // legendtitle.setWrapper(blockcontainer); 175 | // legendtitle.setPosition(RectangleEdge.BOTTOM); 176 | // legendtitle.setHorizontalAlignment(HorizontalAlignment.CENTER); 177 | // chart.addSubtitle(legendtitle); 178 | // chart.getLegend().setVisible(false);// 不显示系统生成的解释性语句 179 | 180 | FileOutputStream fos_jpg = null; 181 | String charName = "时序图.png"; 182 | try { 183 | isChartPathExist(CHART_PATH); 184 | String chartName = CHART_PATH + charName; 185 | fos_jpg = new FileOutputStream(chartName); 186 | 187 | // 将报表保存为png文件 188 | ChartUtilities.writeChartAsPNG(fos_jpg, chart, 800, 510); 189 | 190 | } catch (Exception e) { 191 | e.printStackTrace(); 192 | } finally { 193 | try { 194 | fos_jpg.close(); 195 | } catch (Exception e) { 196 | e.printStackTrace(); 197 | } 198 | } 199 | } 200 | 201 | private XYDataset timeSeriesDataSet2() { 202 | final TimeSeries series = new TimeSeries("Random Second Series -Line"); 203 | 204 | Second current = new Second(); 205 | 206 | double value = 100.0; 207 | for (int i = 0; i < 400; i++) { 208 | try { 209 | if(i % 60 == 0) { 210 | 211 | value = (value + Math.random() - 0.5) * 0.8; 212 | //System.out.println(value); 213 | series.add(current, new Double(value)); 214 | }else { 215 | series.add(current, null); 216 | 217 | } 218 | current = (Second) current.next(); 219 | } catch (SeriesException e) { 220 | System.err.println("Error adding to series"); 221 | } 222 | } 223 | 224 | final XYDataset dataset = (XYDataset) new TimeSeriesCollection(series); 225 | return dataset; 226 | } 227 | 228 | private XYDataset timeSeriesDataSet() { 229 | final TimeSeries series = new TimeSeries("Random Second Series"); 230 | 231 | Second current = new Second(); 232 | 233 | double value = 100.0; 234 | for (int i = 0; i < 400; i++) { 235 | try { 236 | value = value + Math.random() - 0.5; 237 | series.add(current, new Double(value)); 238 | current = (Second) current.next(); 239 | } catch (SeriesException e) { 240 | System.err.println("Error adding to series"); 241 | } 242 | } 243 | 244 | final XYDataset dataset = (XYDataset) new TimeSeriesCollection(series); 245 | return dataset; 246 | } 247 | 248 | 249 | 250 | /** 251 | * 判断文件夹是否存在,如果不存在则新建 252 | * 253 | * @param chartPath 254 | */ 255 | private void isChartPathExist(String chartPath) { 256 | File file = new File(chartPath); 257 | if (!file.exists()) { 258 | file.mkdirs(); 259 | // log.info("CHART_PATH="+CHART_PATH+"create."); 260 | } 261 | } 262 | 263 | 264 | } 265 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/JFreeChartDemoCombined2.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.BasicStroke; 4 | import java.awt.Color; 5 | import java.awt.Font; 6 | import java.io.File; 7 | import java.io.FileOutputStream; 8 | import java.text.SimpleDateFormat; 9 | 10 | import org.jfree.chart.ChartColor; 11 | import org.jfree.chart.ChartFactory; 12 | import org.jfree.chart.ChartUtilities; 13 | import org.jfree.chart.JFreeChart; 14 | import org.jfree.chart.axis.DateAxis; 15 | import org.jfree.chart.axis.DateTickUnit; 16 | import org.jfree.chart.axis.ValueAxis; 17 | import org.jfree.chart.plot.XYPlot; 18 | import org.jfree.chart.renderer.xy.XYItemRenderer; 19 | import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; 20 | import org.jfree.data.general.SeriesException; 21 | import org.jfree.data.time.Day; 22 | import org.jfree.data.time.TimeSeries; 23 | import org.jfree.data.time.TimeSeriesCollection; 24 | import org.jfree.data.xy.XYDataset; 25 | 26 | public class JFreeChartDemoCombined2 { 27 | 28 | private static final String CHART_PATH = "E:\\file\\JFreeChart\\demo\\"; 29 | 30 | public static void main(String[] args) { 31 | JFreeChartDemoCombined2 pm = new JFreeChartDemoCombined2(); 32 | // 生成时序图 33 | pm.makeTimeSeriesChart(); 34 | 35 | System.err.println("Jfree Chart Run Over..."); 36 | } 37 | 38 | public void makeTimeSeriesChart() { 39 | 40 | JFreeChart chart = ChartFactory.createTimeSeriesChart("时序图折线图", "X/秒", "Y值", createDataset(), true, true, false); 41 | XYPlot plot = chart.getXYPlot(); 42 | 43 | plot.setDomainGridlinePaint(Color.LIGHT_GRAY); 44 | plot.setRangeGridlinePaint(Color.LIGHT_GRAY); 45 | 46 | // plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); 47 | XYItemRenderer r = plot.getRenderer(); 48 | if (r instanceof XYLineAndShapeRenderer) { 49 | XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; 50 | renderer.setBaseShapesVisible(false); 51 | renderer.setBaseShapesFilled(false); 52 | renderer.setSeriesStroke(0, new BasicStroke(0.8f));//画笔 53 | renderer.setSeriesStroke(1, new BasicStroke(1f));//画笔 54 | renderer.setSeriesPaint(0, Color.red); //颜色 ---密集 55 | renderer.setSeriesPaint(1, Color.pink); //颜色--折线 56 | } 57 | 58 | // 设置总的背景颜色 59 | chart.setBackgroundPaint(ChartColor.WHITE); 60 | // 设置标题颜色 61 | chart.getTitle().setPaint(ChartColor.BLACK); 62 | // 设置图的背景颜色 63 | plot.setBackgroundPaint(ChartColor.WHITE); 64 | 65 | // 设置表格线颜色 66 | // p.setRangeGridlinePaint(ChartColor.red); 67 | // 对X轴做操作 68 | DateAxis domainAxis = (DateAxis) plot.getDomainAxis(); //x轴设置 69 | domainAxis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 40, new SimpleDateFormat("MM-dd"))); 70 | //DateAxis domainAxis = (DateAxis) plot.getDomainAxis(); 71 | domainAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 13));// 设置X轴坐标上的文字 72 | domainAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置X轴的标题文字 73 | domainAxis.setVerticalTickLabels(true); 74 | 75 | // 对Y轴做操作 76 | ValueAxis rAxis = plot.getRangeAxis(); 77 | rAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 14)); // 设置Y轴坐标上的文字 78 | rAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置Y轴的标题文字 79 | rAxis.setUpperMargin(0.25);// 设置最高的一个 Item 与图片顶端的距离 80 | 81 | //对Title 操作 82 | chart.getTitle().setFont(new Font("黑体", Font.PLAIN, 15)); 83 | //对Legend 操作 84 | chart.getLegend().setItemFont(new Font("黑体", Font.PLAIN, 15)); 85 | 86 | // 设置总的背景颜色 87 | chart.setBackgroundPaint(ChartColor.WHITE); 88 | 89 | // 设置图的背景颜色 90 | plot.setBackgroundPaint(ChartColor.WHITE); 91 | 92 | //设置网格不可见 93 | plot.setDomainGridlinesVisible(false); 94 | plot.setRangeGridlinesVisible(false); 95 | 96 | FileOutputStream outStream = null; 97 | String charName = "时序图.png"; 98 | try { 99 | isChartPathExist(CHART_PATH); 100 | String chartName = CHART_PATH + charName; 101 | outStream = new FileOutputStream(chartName); 102 | 103 | // 将报表保存为png文件 104 | ChartUtilities.writeChartAsPNG(outStream, chart, 800, 510); 105 | 106 | } catch (Exception e) { 107 | e.printStackTrace(); 108 | } finally { 109 | try { 110 | outStream.close(); 111 | } catch (Exception e) { 112 | e.printStackTrace(); 113 | } 114 | } 115 | } 116 | 117 | 118 | 119 | @SuppressWarnings("deprecation") 120 | private static XYDataset createDataset() { 121 | TimeSeriesCollection dataset = new TimeSeriesCollection(); 122 | 123 | TimeSeries timeSeries1 = new TimeSeries("A 时序图", Day.class); 124 | TimeSeries timeSeries2 = new TimeSeries("B 折线图", Day.class); 125 | TimeSeries timeSeries3 = new TimeSeries("C 折线图", Day.class); 126 | TimeSeries timeSeries4 = new TimeSeries("D 折线图", Day.class); 127 | TimeSeries timeSeries5 = new TimeSeries("E 折线图", Day.class); 128 | 129 | 130 | Day current = new Day(); 131 | 132 | double value = 100.0; 133 | 134 | for (int i = 0; i < 800; i++) { 135 | try { 136 | value = value + Math.random() - 0.5; 137 | timeSeries1.add(current, new Double(value)); 138 | if(value>=100) { 139 | value = 100.0d; 140 | } 141 | 142 | if(i % 40 ==0 || i == 799) { 143 | timeSeries2.add(current, new Double(value)); 144 | } 145 | if(i % 50 ==0 || i == 799) { 146 | timeSeries3.add(current, new Double(value)); 147 | } 148 | if(i % 60 ==0 || i == 799) { 149 | timeSeries4.add(current, new Double(value)); 150 | } 151 | if(i % 80 ==0 || i == 799) { 152 | timeSeries5.add(current, new Double(value)); 153 | } 154 | current = (Day) current.next(); 155 | } catch (SeriesException e) { 156 | e.printStackTrace(); 157 | } 158 | } 159 | dataset.addSeries(timeSeries1); 160 | dataset.addSeries(timeSeries2); 161 | dataset.addSeries(timeSeries3); 162 | dataset.addSeries(timeSeries4); 163 | dataset.addSeries(timeSeries5); 164 | return dataset; 165 | 166 | } 167 | 168 | 169 | /** 170 | * 判断文件夹是否存在,如果不存在则新建 171 | * 172 | * @param chartPath 173 | */ 174 | private void isChartPathExist(String chartPath) { 175 | File file = new File(chartPath); 176 | if (!file.exists()) { 177 | file.mkdirs(); 178 | // log.info("CHART_PATH="+CHART_PATH+"create."); 179 | } 180 | } 181 | 182 | 183 | } 184 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/LayeredBarChartDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.*; 4 | import java.io.FileOutputStream; 5 | 6 | import javax.swing.JPanel; 7 | import org.jfree.chart.*; 8 | import org.jfree.chart.axis.CategoryAxis; 9 | import org.jfree.chart.axis.NumberAxis; 10 | import org.jfree.chart.plot.CategoryPlot; 11 | import org.jfree.chart.plot.PlotOrientation; 12 | import org.jfree.chart.renderer.category.LayeredBarRenderer; 13 | import org.jfree.data.category.CategoryDataset; 14 | import org.jfree.data.category.DefaultCategoryDataset; 15 | import org.jfree.ui.ApplicationFrame; 16 | import org.jfree.ui.RefineryUtilities; 17 | import org.jfree.util.SortOrder; 18 | 19 | @SuppressWarnings("serial") 20 | public class LayeredBarChartDemo extends ApplicationFrame { 21 | 22 | public LayeredBarChartDemo(String s) { 23 | super(s); 24 | JPanel jpanel = createDemoPanel(); 25 | jpanel.setPreferredSize(new Dimension(500, 270)); 26 | setContentPane(jpanel); 27 | } 28 | 29 | /** 30 | * 生成显示图形用的数据集 31 | * 32 | * @return 33 | */ 34 | private static CategoryDataset createDataset() { 35 | // 图例 36 | String s1 = "One"; 37 | String s2 = "Two"; 38 | String s3 = "Thr"; 39 | // 横坐标分类 40 | String t1 = "C1"; 41 | String t2 = "C2"; 42 | String t3 = "C3"; 43 | String t4 = "C4"; 44 | String t5 = "C5"; 45 | 46 | DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset(); 47 | 48 | // addValue方法说明:参数1:柱状图显示的量 49 | // 参数2:柱子(或图例)标注(一个点显示一个柱子时,只需要一个) 50 | // 参数3:横坐标上显示的分类 51 | defaultcategorydataset.addValue(1D, s1, t1); 52 | defaultcategorydataset.addValue(3D, s1, t2); 53 | defaultcategorydataset.addValue(2D, s1, t3); 54 | defaultcategorydataset.addValue(5D, s1, t4); 55 | defaultcategorydataset.addValue(8D, s1, t5); 56 | defaultcategorydataset.addValue(5D, s2, t1); 57 | defaultcategorydataset.addValue(9D, s2, t2); 58 | defaultcategorydataset.addValue(6D, s2, t3); 59 | defaultcategorydataset.addValue(1D, s2, t4); 60 | defaultcategorydataset.addValue(5D, s2, t5); 61 | defaultcategorydataset.addValue(8D, s3, t1); 62 | defaultcategorydataset.addValue(1D, s3, t2); 63 | defaultcategorydataset.addValue(5D, s3, t3); 64 | defaultcategorydataset.addValue(2D, s3, t4); 65 | defaultcategorydataset.addValue(6D, s3, t5); 66 | return defaultcategorydataset; 67 | } 68 | 69 | /** 70 | * 绘制图形,设置参数 71 | * 72 | * @param categorydataset 73 | * @return 74 | */ 75 | private static JFreeChart createChart(CategoryDataset categorydataset) { 76 | // 生成图形--参数说明 77 | // 参数1:标题 78 | // 参数2:分类 79 | // 参数3:值 80 | // 参数4:数据集 81 | // 参数5:柱子的显示方向 82 | // 参数6:是否显示图例 83 | // 参数7:暂不知道 84 | // 参数8:是否显示URL 85 | JFreeChart jfreechart = ChartFactory.createBarChart("BarImage", "CCC", "Value", categorydataset, PlotOrientation.VERTICAL, true, true, true); 86 | // 设置背景色 87 | jfreechart.setBackgroundPaint(Color.lightGray); 88 | // 设置图形对象 89 | CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot(); 90 | // 设置图形的背景色 91 | categoryplot.setBackgroundPaint(Color.yellow); 92 | // 设置图形上竖线的颜色 93 | categoryplot.setDomainGridlinePaint(Color.black); 94 | // 设置图形上竖线是否显示 95 | categoryplot.setDomainGridlinesVisible(true); 96 | // 设置图形上横线的颜色 97 | categoryplot.setRangeGridlinePaint(Color.black); 98 | // 获取横轴 99 | CategoryAxis categoryAxis = categoryplot.getDomainAxis(); 100 | // 设置横坐标上的分类是否显示 101 | categoryAxis.setTickLabelsVisible(true); 102 | // 获取纵轴 103 | NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); 104 | // 设置纵轴的刻度线 105 | numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 106 | LayeredBarRenderer layeredbarrenderer = new LayeredBarRenderer(); 107 | layeredbarrenderer.setDrawBarOutline(false); 108 | // 设置柱子的边框是否显示 109 | categoryplot.setRenderer(layeredbarrenderer); 110 | // 设置柱子的排序方式 111 | categoryplot.setRowRenderingOrder(SortOrder.DESCENDING); 112 | GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F, Color.black, 0.0F, 0.0F, new Color(0, 0, 64)); 113 | GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 64, 0)); 114 | GradientPaint gradientpaint3 = new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0)); 115 | // 设置柱子的颜色 116 | layeredbarrenderer.setSeriesPaint(0, gradientpaint1); 117 | layeredbarrenderer.setSeriesPaint(1, gradientpaint2); 118 | layeredbarrenderer.setSeriesPaint(2, gradientpaint3); 119 | return jfreechart; 120 | } 121 | 122 | 123 | private static final String CHART_PATH = "E:\\file\\JFreeChart\\demo\\"; 124 | public static JPanel createDemoPanel() { 125 | JFreeChart jfreechart = createChart(createDataset()); 126 | FileOutputStream fos_jpg = null; 127 | String charName ="panel.png"; 128 | try { 129 | String chartName = CHART_PATH + charName; 130 | fos_jpg = new FileOutputStream(chartName); 131 | 132 | // 将报表保存为png文件 133 | ChartUtilities.writeChartAsPNG(fos_jpg, jfreechart, 800, 510); 134 | 135 | } catch (Exception e) { 136 | e.printStackTrace(); 137 | } finally { 138 | try { 139 | fos_jpg.close(); 140 | } catch (Exception e) { 141 | e.printStackTrace(); 142 | } 143 | } 144 | return new ChartPanel(jfreechart); 145 | } 146 | 147 | public static void main(String args[]) { 148 | LayeredBarChartDemo layeredbarchartdemo1 = new LayeredBarChartDemo("LayeredBarChart"); 149 | layeredbarchartdemo1.pack(); 150 | RefineryUtilities.centerFrameOnScreen(layeredbarchartdemo1); 151 | layeredbarchartdemo1.setVisible(true); 152 | } 153 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/LineChart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | 6 | import org.jfree.chart.ChartFactory; 7 | import org.jfree.chart.JFreeChart; 8 | import org.jfree.chart.axis.CategoryAxis; 9 | import org.jfree.chart.axis.CategoryLabelPositions; 10 | import org.jfree.chart.axis.NumberAxis; 11 | import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; 12 | import org.jfree.chart.plot.CategoryPlot; 13 | import org.jfree.chart.plot.PlotOrientation; 14 | import org.jfree.chart.renderer.category.LineAndShapeRenderer; 15 | import org.jfree.data.category.CategoryDataset; 16 | 17 | /** 18 | * 折线图 19 | * 20 | * @author huozhicheng@gmail.com 21 | * @date 2013-1-11上午11:02:16 22 | * @version 1.0 23 | */ 24 | public class LineChart { 25 | 26 | /** 27 | * 生成折线图 28 | * @param chartTitle 图的标题 29 | * @param x 横轴标题 30 | * @param y 纵轴标题 31 | * @param dataset 数据集 32 | * @return 33 | */ 34 | public static JFreeChart createLineChart(String chartTitle, String x, String y, CategoryDataset dataset) { 35 | 36 | // 构建一个chart 37 | JFreeChart chart = ChartFactory.createLineChart( 38 | chartTitle, 39 | x, 40 | y, 41 | dataset, 42 | PlotOrientation.VERTICAL, 43 | true, 44 | true, 45 | false); 46 | //字体清晰 47 | chart.setTextAntiAlias(false); 48 | // 设置背景颜色 49 | chart.setBackgroundPaint(Color.WHITE); 50 | 51 | // 设置图标题的字体 52 | Font font = new Font("隶书", Font.BOLD, 25); 53 | chart.getTitle().setFont(font); 54 | 55 | // 设置面板字体 56 | Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); 57 | // 设置图示的字体 58 | chart.getLegend().setItemFont(labelFont); 59 | 60 | CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); 61 | // x轴 // 分类轴网格是否可见 62 | categoryplot.setDomainGridlinesVisible(true); 63 | // y轴 //数据轴网格是否可见 64 | categoryplot.setRangeGridlinesVisible(true); 65 | categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩 66 | categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩 67 | categoryplot.setBackgroundPaint(Color.lightGray);// 折线图的背景颜色 68 | 69 | // 设置轴和面板之间的距离 70 | // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); 71 | 72 | // 横轴 x 73 | CategoryAxis domainAxis = categoryplot.getDomainAxis(); 74 | domainAxis.setLabelFont(labelFont);// 轴标题 75 | domainAxis.setTickLabelFont(labelFont);// 轴数值 76 | // domainAxis.setLabelPaint(Color.BLUE);//轴标题的颜色 77 | // domainAxis.setTickLabelPaint(Color.BLUE);//轴数值的颜色 78 | 79 | // 横轴 lable 的位置 横轴上的 Lable 45度倾斜 DOWN_45 80 | domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD); 81 | 82 | // 设置距离图片左端距离 83 | domainAxis.setLowerMargin(0.0); 84 | // 设置距离图片右端距离 85 | domainAxis.setUpperMargin(0.0); 86 | 87 | // 纵轴 y 88 | NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); 89 | numberaxis.setLabelFont(labelFont); 90 | numberaxis.setTickLabelFont(labelFont); 91 | numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); 92 | numberaxis.setAutoRangeIncludesZero(true); 93 | 94 | // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!! 95 | LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot 96 | .getRenderer(); 97 | lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见 98 | lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见 99 | 100 | // 显示折点数据 101 | lineandshaperenderer 102 | .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); 103 | lineandshaperenderer.setBaseItemLabelsVisible(true); 104 | 105 | return chart; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/Piechart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.RenderingHints; 6 | import java.text.DecimalFormat; 7 | import java.text.NumberFormat; 8 | 9 | import org.jfree.chart.ChartFactory; 10 | import org.jfree.chart.JFreeChart; 11 | import org.jfree.chart.labels.StandardPieSectionLabelGenerator; 12 | import org.jfree.chart.plot.PiePlot3D; 13 | import org.jfree.data.general.DefaultPieDataset; 14 | import org.jfree.data.general.PieDataset; 15 | 16 | /** 17 | * 饼图 18 | * 19 | * @author huozhicheng@gmail.com 20 | * @date 2013-1-10下午5:06:36 21 | * @version 1.0 22 | */ 23 | public class Piechart { 24 | 25 | /** 26 | * 生成饼图 27 | * @param chartTitle 图的标题 28 | * @param dataset 数据集 29 | * @param pieKeys 分饼的名字集 30 | * @return 31 | */ 32 | public static JFreeChart createPieChart3D(String chartTitle,PieDataset dataset, String[] pieKeys) { 33 | 34 | JFreeChart chart = ChartFactory.createPieChart3D( 35 | chartTitle, 36 | dataset, 37 | true,//显示图例 38 | true, 39 | false); 40 | 41 | //关闭抗锯齿,是字体清晰 42 | chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); 43 | chart.setTextAntiAlias(false); 44 | //图片背景色 45 | chart.setBackgroundPaint(Color.white); 46 | //设置图标题的字体重新设置title 47 | Font font = new Font("隶书", Font.BOLD, 25); 48 | chart.getTitle().setFont(font); 49 | /*TextTitle title = new TextTitle(chartTitle); 50 | title.setFont(font); 51 | chart.setTitle(title);*/ 52 | //设置图例字体 53 | chart.getLegend().setItemFont(new Font("宋体",Font.PLAIN,14)); 54 | 55 | PiePlot3D plot = (PiePlot3D) chart.getPlot(); 56 | // 图片中显示百分比:默认方式 57 | 58 | // 指定饼图轮廓线的颜色 59 | // plot.setBaseSectionOutlinePaint(Color.BLACK); 60 | // plot.setBaseSectionPaint(Color.BLACK); 61 | 62 | // 设置无数据时的信息 63 | plot.setNoDataMessage("无对应的数据,请重新查询。"); 64 | 65 | // 设置无数据时的信息显示颜色 66 | plot.setNoDataMessagePaint(Color.red); 67 | 68 | // 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位 69 | plot.setLabelGenerator(new StandardPieSectionLabelGenerator( 70 | "{0}={1}({2})", NumberFormat.getNumberInstance(), 71 | new DecimalFormat("0.00%"))); 72 | //图片显示字体 73 | plot.setLabelFont(new Font("宋体", Font.TRUETYPE_FONT, 12)); 74 | 75 | // 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例 76 | plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator( 77 | "{0}={1}({2})")); 78 | 79 | 80 | // 指定图片的透明度(0.0-1.0) 81 | plot.setForegroundAlpha(0.65f); 82 | // 指定显示的饼图上圆形(false)还椭圆形(true) 83 | plot.setCircular(false, true); 84 | 85 | // 设置第一个 饼块section 的开始位置,默认是12点钟方向 86 | plot.setStartAngle(90); 87 | 88 | // // 设置分饼颜色 89 | plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144)); 90 | plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144)); 91 | 92 | return chart; 93 | } 94 | // 饼状图 数据集 95 | public static PieDataset getDataPieSetByUtil(double[] data, 96 | String[] datadescription) { 97 | 98 | if (data != null && datadescription != null) { 99 | if (data.length == datadescription.length) { 100 | DefaultPieDataset dataset = new DefaultPieDataset(); 101 | for (int i = 0; i < data.length; i++) { 102 | dataset.setValue(datadescription[i], data[i]); 103 | } 104 | return dataset; 105 | } 106 | } 107 | return null; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/TestTimeSeriesChart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | 6 | import org.jfree.chart.ChartColor; 7 | import org.jfree.chart.ChartFactory; 8 | import org.jfree.chart.ChartFrame; 9 | import org.jfree.chart.JFreeChart; 10 | import org.jfree.chart.axis.DateAxis; 11 | import org.jfree.chart.axis.ValueAxis; 12 | import org.jfree.chart.plot.XYPlot; 13 | import org.jfree.chart.renderer.xy.XYItemRenderer; 14 | import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; 15 | import org.jfree.data.time.Day; 16 | import org.jfree.data.time.Hour; 17 | import org.jfree.data.time.Minute; 18 | import org.jfree.data.time.TimeSeries; 19 | import org.jfree.data.time.TimeSeriesCollection; 20 | import org.jfree.data.xy.XYDataset; 21 | 22 | public class TestTimeSeriesChart { 23 | 24 | private static XYDataset createDataset() { 25 | TimeSeriesCollection dataset = new TimeSeriesCollection(); 26 | Day day = new Day(21, 9, 2008); 27 | Hour hour22 = new Hour(22, day); 28 | Hour hour23 = new Hour(23, day); 29 | 30 | TimeSeries timeSeries1 = new TimeSeries("篮球火", Minute.class); 31 | timeSeries1.add(new Minute(25, hour23), 2.80); 32 | timeSeries1.add(new Minute(22, hour23), 2.59); 33 | timeSeries1.add(new Minute(32, hour22), 2.38); 34 | timeSeries1.add(new Minute(14, hour22), 2.35); 35 | timeSeries1.add(new Minute(18, hour23), 2.34); 36 | timeSeries1.add(new Minute(57, hour23), 2.31); 37 | timeSeries1.add(new Minute(14, hour23), 2.28); 38 | timeSeries1.add(new Minute(23, hour22), 2.25); 39 | timeSeries1.add(new Minute(46, hour22), 2.16); 40 | timeSeries1.add(new Minute(40, hour22), 2.16); 41 | timeSeries1.add(new Minute(6, hour22), 1.95); 42 | timeSeries1.add(new Minute(51, hour22), 1.93); 43 | timeSeries1.add(new Minute(2, hour23), 1.86); 44 | timeSeries1.add(new Minute(6, hour23), 1.84); 45 | timeSeries1.add(new Minute(9, hour23), 1.79); 46 | timeSeries1.add(new Minute(29, hour23), 1.72); 47 | 48 | TimeSeries timeSeries2 = new TimeSeries("无敌珊宝妹", Minute.class); 49 | timeSeries2.add(new Minute(36, hour22), 3.63); 50 | timeSeries2.add(new Minute(55, hour22), 3.63); 51 | timeSeries2.add(new Minute(21, hour23), 3.36); 52 | timeSeries2.add(new Minute(30, hour22), 3.28); 53 | timeSeries2.add(new Minute(33, hour23), 3.18); 54 | timeSeries2.add(new Minute(6, hour23), 3.13); 55 | timeSeries2.add(new Minute(13, hour22), 3.05); 56 | timeSeries2.add(new Minute(0, hour23), 2.98); 57 | timeSeries2.add(new Minute(40, hour22), 2.98); 58 | timeSeries2.add(new Minute(48, hour22), 2.91); 59 | timeSeries2.add(new Minute(14, hour23), 2.73); 60 | timeSeries2.add(new Minute(27, hour23), 2.59); 61 | timeSeries2.add(new Minute(38, hour23), 2.37); 62 | 63 | TimeSeries timeSeries3 = new TimeSeries("不良笑花", Minute.class); 64 | timeSeries3.add(new Minute(8, hour23), 2.84); 65 | timeSeries3.add(new Minute(29, hour22), 2.51); 66 | timeSeries3.add(new Minute(56, hour22), 2.23); 67 | timeSeries3.add(new Minute(5, hour23), 2.17); 68 | timeSeries3.add(new Minute(47, hour22), 2.10); 69 | timeSeries3.add(new Minute(17, hour22), 1.86); 70 | timeSeries3.add(new Minute(24, hour23), 1.84); 71 | timeSeries3.add(new Minute(5, hour22), 1.84); 72 | timeSeries3.add(new Minute(15, hour23), 1.73); 73 | timeSeries3.add(new Minute(36, hour22), 1.46); 74 | 75 | dataset.addSeries(timeSeries1); 76 | dataset.addSeries(timeSeries2); 77 | dataset.addSeries(timeSeries3); 78 | return dataset; 79 | } 80 | 81 | public static void createTimeSeriesChart() { 82 | JFreeChart timeSeriesChart = ChartFactory.createTimeSeriesChart("电视剧收视率", "播放时间", "收视率百分点", createDataset(), true, 83 | true, false); 84 | timeSeriesChart.setBackgroundPaint(Color.white); 85 | XYPlot plot = timeSeriesChart.getXYPlot(); 86 | setXYPolt(plot); 87 | // 对X轴做操作 88 | DateAxis domainAxis = (DateAxis) plot.getDomainAxis(); 89 | domainAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 13));// 设置X轴坐标上的文字 90 | domainAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置X轴的标题文字 91 | 92 | // 对Y轴做操作 93 | ValueAxis rAxis = plot.getRangeAxis(); 94 | rAxis.setTickLabelFont(new Font("黑体", Font.PLAIN, 14)); // 设置Y轴坐标上的文字 95 | rAxis.setLabelFont(new Font("黑体", Font.PLAIN, 15)); // 设置Y轴的标题文字 96 | rAxis.setUpperMargin(0.25);// 设置最高的一个 Item 与图片顶端的距离 97 | 98 | //对Title 操作 99 | timeSeriesChart.getTitle().setFont(new Font("黑体", Font.PLAIN, 15)); 100 | //对Legend 操作 101 | timeSeriesChart.getLegend().setItemFont(new Font("黑体", Font.PLAIN, 15)); 102 | 103 | // 设置总的背景颜色 104 | timeSeriesChart.setBackgroundPaint(ChartColor.WHITE); 105 | 106 | // 设置图的背景颜色 107 | plot.setBackgroundPaint(ChartColor.WHITE); 108 | 109 | //设置网格不可见 110 | plot.setDomainGridlinesVisible(false); 111 | plot.setRangeGridlinesVisible(false); 112 | 113 | ChartFrame frame = new ChartFrame("TestPieChart", timeSeriesChart,false); 114 | 115 | frame.pack(); 116 | frame.setVisible(true); 117 | } 118 | 119 | public static void setXYPolt(XYPlot plot) { 120 | plot.setDomainGridlinePaint(Color.LIGHT_GRAY); 121 | plot.setRangeGridlinePaint(Color.LIGHT_GRAY); 122 | 123 | // plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); 124 | XYItemRenderer r = plot.getRenderer(); 125 | if (r instanceof XYLineAndShapeRenderer) { 126 | XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; 127 | renderer.setBaseShapesVisible(false); 128 | renderer.setBaseShapesFilled(false); 129 | } 130 | } 131 | 132 | public static void main(String[] args) { 133 | createTimeSeriesChart(); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/jfreechart/TimeSeriesChart.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.jfreechart; 2 | //package com.example.demo; 3 | // 4 | //import java.text.SimpleDateFormat; 5 | //import java.util.Random; 6 | //import java.util.Vector; 7 | // 8 | //import javax.swing.JFrame; 9 | //import javax.swing.SwingUtilities; 10 | // 11 | //import org.jfree.chart.ChartFactory; 12 | //import org.jfree.chart.ChartPanel; 13 | //import org.jfree.chart.JFreeChart; 14 | //import org.jfree.chart.axis.DateAxis; 15 | //import org.jfree.chart.axis.DateTickUnit; 16 | //import org.jfree.chart.axis.DateTickUnitType; 17 | //import org.jfree.chart.plot.XYPlot; 18 | //import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; 19 | //import org.jfree.data.time.TimeSeries; 20 | //import org.jfree.data.time.TimeSeriesCollection; 21 | // 22 | // 23 | // 24 | //public class TimeSeriesChart { 25 | // public TimeSeriesChart() { 26 | // } 27 | // 28 | // /** 29 | // * 创建数据集合 30 | // */ 31 | // public TimeSeriesCollection createDataset() { 32 | // TimeSeriesCollection dataset = new TimeSeriesCollection(); 33 | // String[] categories = { "dataA", "dataB" }; 34 | // 35 | // Random random = new Random(); 36 | // for (int row = 0; row < categories.length; row++) { 37 | // Vector dateValues = new Vector(); 38 | // for (int i = 0; i < 200; i++) { 39 | // String date = (2000 + i) + "-0" + i + "-21"; 40 | // System.out.println(date); 41 | // Object[] dateValue = { date, random.nextInt(100)+i/20*20 }; 42 | // dateValues.add(dateValue); 43 | // 44 | // } 45 | // TimeSeries timeSeries = ChartUtils.createTimeseries(categories[row], dateValues); 46 | // dataset.addSeries(timeSeries); 47 | // } 48 | // return dataset; 49 | // } 50 | // 51 | // public ChartPanel createChart() { 52 | // // 2:创建Chart[创建不同图形] 53 | // TimeSeriesCollection dataset = createDataset(); 54 | // JFreeChart chart = ChartFactory.createTimeSeriesChart("哎哎哎", "", "", dataset, false, false, false); 55 | // // 3:设置抗锯齿,防止字体显示不清楚 56 | // ChartUtils.setAntiAlias(chart);// 抗锯齿 57 | // // 4:对柱子进行渲染[创建不同图形] 58 | // ChartUtils.setTimeSeriesRender(chart.getPlot(), false, true); 59 | // // 5:对其他部分进行渲染 60 | // XYPlot xyplot = (XYPlot) chart.getPlot(); 61 | // ChartUtils.setXY_XAixs(xyplot); 62 | // ChartUtils.setXY_YAixs(xyplot); 63 | // // 日期X坐标轴 64 | // DateAxis domainAxis = (DateAxis) xyplot.getDomainAxis(); 65 | // domainAxis.setAutoTickUnitSelection(false); 66 | // DateTickUnit dateTickUnit = null; 67 | // if (dataset.getItemCount(0) < 16) { 68 | // //刻度单位月,半年为间隔 69 | // dateTickUnit = new DateTickUnit(DateTickUnitType.MONTH, 6, new SimpleDateFormat("yyyy-MM")); // 第二个参数是时间轴间距 70 | // } else {// 数据过多,不显示数据 71 | // XYLineAndShapeRenderer xyRenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); 72 | // xyRenderer.setBaseItemLabelsVisible(false); 73 | // //设置曲线是否显示数据节点 74 | // xyRenderer.setBaseShapesVisible(false); 75 | // dateTickUnit = new DateTickUnit(DateTickUnitType.YEAR, 1, new SimpleDateFormat("yyyy")); // 第二个参数是时间轴间距 76 | // } 77 | // // 设置时间单位 78 | // domainAxis.setTickUnit(dateTickUnit); 79 | //// ChartUtils.setLegendEmptyBorder(chart); 80 | // // 设置图例位置 81 | // // 6:使用chartPanel接收 82 | // ChartPanel chartPanel = new ChartPanel(chart); 83 | // chartPanel.setMouseZoomable(true, false); 84 | // return chartPanel; 85 | // } 86 | // 87 | // public static void main(String[] args) { 88 | // final JFrame frame = new JFrame(); 89 | // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 90 | // frame.setSize(1024, 420); 91 | // frame.setLocationRelativeTo(null); 92 | // 93 | // SwingUtilities.invokeLater(new Runnable() { 94 | // @Override 95 | // public void run() { 96 | // // 创建图形 97 | // ChartPanel chartPanel = new TimeSeriesChart().createChart(); 98 | // frame.getContentPane().add(chartPanel); 99 | // frame.setVisible(true); 100 | // } 101 | // }); 102 | // 103 | // } 104 | // 105 | //} 106 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/lambda/LambdaTest.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.lambda; 2 | 3 | import java.util.Arrays; 4 | import java.util.IntSummaryStatistics; 5 | import java.util.List; 6 | import java.util.function.Predicate; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | * http://www.jdon.com/idea/java/10-example-of-lambda-expressions-in-java8.html 11 | */ 12 | public class LambdaTest { 13 | 14 | public static void main(String[] args) { 15 | //线程的lambda使用 16 | new Thread(() -> { 17 | System.out.println("我是多线程:Hello Lambda"); 18 | }).start(); 19 | 20 | 21 | List features = Arrays.asList("Lambda", "Default-Method", "System-Api", "Date and Time A", "java", "jack", "json"); 22 | for (String f : features) { 23 | System.out.println(f); 24 | } 25 | //集合的lambda使用 26 | features.forEach((n) -> { 27 | System.out.println(n); 28 | }); 29 | 30 | System.out.println("++++++++++++++++++++++++++++++++++++++++++++"); 31 | filter(features, (str) -> str.toString().startsWith("D")); 32 | 33 | 34 | //以j大头, 字符长度为4个字符的字符串 35 | Predicate startWithJ = (s) -> s.startsWith("j"); 36 | Predicate fourLetter = (s) -> s.length() == 4; 37 | 38 | features.stream().filter(startWithJ.and(fourLetter)).forEach((n) -> { 39 | System.out.println(n); 40 | }); 41 | 42 | 43 | System.out.println("++++++++++++++++++++++++map reduce"); 44 | //map reduce 45 | List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500); 46 | for (Integer cost : costBeforeTax) { 47 | double price = cost + .12 * cost; 48 | System.out.println(price); 49 | } 50 | 51 | costBeforeTax.stream().map((c) -> c + 0.12 * c).forEach(System.out::println); 52 | 53 | 54 | double bill = costBeforeTax.stream() 55 | .map((c) -> c + 0.12 * c) 56 | .reduce((sum, c) -> sum + c) 57 | .get(); 58 | 59 | System.out.println("bill:"+ bill); 60 | 61 | 62 | 63 | System.out.println("collect 方法"); 64 | List collect = features.stream().filter(x -> x.length() > 4).collect(Collectors.toList()); 65 | System.out.println(collect); 66 | 67 | List G7 = Arrays.asList("USA", "Japan", "France", "Germany","Italy", "U.K.","Canada"); 68 | String joinStr = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(",")); 69 | System.out.println(joinStr); 70 | 71 | 72 | List numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4); 73 | List powList = numbers.stream().map((i) -> i * i).distinct().collect(Collectors.toList()); 74 | System.out.println("对平方进行distinct:"+ powList); 75 | 76 | IntSummaryStatistics intSummaryStatistics = numbers.stream().mapToInt((x) -> x).summaryStatistics(); 77 | System.out.println("max :"+ intSummaryStatistics.getMax()); 78 | System.out.println("main :"+ intSummaryStatistics.getMin()); 79 | System.out.println("average :"+ intSummaryStatistics.getAverage()); 80 | System.out.println("sum :"+ intSummaryStatistics.getSum()); 81 | 82 | } 83 | 84 | @SuppressWarnings({ "rawtypes", "unchecked" }) 85 | public static void filter(List list, Predicate predicate) { 86 | list.stream().filter((l) -> (predicate.test(l))).forEach((l) -> { 87 | System.out.println(l); 88 | }); 89 | } 90 | 91 | } 92 | 93 | 94 | /** 95 | * 你可以使用 下面语法实现Lambda: 96 | *

97 | * (params) -> expression 98 | * (params) -> statement 99 | * (params) -> { statements } 100 | *

101 | * 带参数的例子可以在:baseController.java中找到 102 | */ -------------------------------------------------------------------------------- /src/main/java/com/example/demo/lambda/TestMap.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.lambda; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class TestMap { 7 | public static void main(String[] args) { 8 | Map map = new HashMap<>(); 9 | map.put("java", "script"); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/listener/RequestListenerDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.listener; 2 | 3 | import javax.servlet.ServletRequestEvent; 4 | import javax.servlet.ServletRequestListener; 5 | import javax.servlet.annotation.WebListener; 6 | 7 | @WebListener 8 | public class RequestListenerDemo implements ServletRequestListener{ 9 | 10 | @Override 11 | public void requestDestroyed(ServletRequestEvent sre) { 12 | System.err.println("request destroy"); 13 | } 14 | 15 | @Override 16 | public void requestInitialized(ServletRequestEvent sre) { 17 | System.err.println("request init"); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/listener/ServletContextListenerDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.listener; 2 | 3 | import javax.servlet.ServletContextEvent; 4 | import javax.servlet.ServletContextListener; 5 | import javax.servlet.annotation.WebListener; 6 | 7 | @WebListener 8 | public class ServletContextListenerDemo implements ServletContextListener { 9 | 10 | @Override 11 | public void contextInitialized(ServletContextEvent sce) { 12 | System.err.println("-1.ServletContextListener init"); 13 | } 14 | 15 | @Override 16 | public void contextDestroyed(ServletContextEvent sce) { 17 | System.err.println("ServletContextListener destroy"); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/listener/SessionListenerDemo.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.listener; 2 | 3 | import javax.servlet.annotation.WebListener; 4 | import javax.servlet.http.HttpSessionEvent; 5 | import javax.servlet.http.HttpSessionListener; 6 | 7 | @WebListener 8 | public class SessionListenerDemo implements HttpSessionListener { 9 | 10 | @Override 11 | public void sessionCreated(HttpSessionEvent se) { 12 | System.err.println("3.session listener.."); 13 | } 14 | 15 | @Override 16 | public void sessionDestroyed(HttpSessionEvent se) { 17 | System.err.println("session 被销毁"); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/pagination/PaginationFormatting.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.pagination; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.data.domain.Page; 7 | import org.springframework.data.domain.Pageable; 8 | 9 | import com.example.demo.bean.Persons; 10 | import com.example.demo.repository.PersonsRepository; 11 | import com.example.demo.utils.SpringUtil; 12 | 13 | 14 | interface Types { 15 | 16 | public Page query(); 17 | 18 | public Integer getCount(); 19 | 20 | public Integer getPageNumber(); 21 | 22 | public Long getTotal(); 23 | 24 | public Object getContent(); 25 | } 26 | 27 | class BasePaginationInfo { 28 | 29 | public Pageable pageable; 30 | 31 | public PersonsRepository instance = SpringUtil.getBean(PersonsRepository.class); 32 | 33 | public String sex, email; 34 | 35 | public BasePaginationInfo(String sexName, String emailName, Pageable pageable) { 36 | 37 | this.pageable = pageable; 38 | 39 | this.sex = sexName; 40 | 41 | this.email = emailName; 42 | } 43 | } 44 | 45 | class AllType extends BasePaginationInfo implements Types { 46 | 47 | 48 | public AllType(String sexName, String emailName, Pageable pageable) { //String sexName, String emailName, 49 | 50 | super(sexName, emailName, pageable); 51 | 52 | } 53 | 54 | public Page query() { 55 | 56 | return this.instance.findAll( 57 | 58 | this.pageable 59 | 60 | ); 61 | } 62 | 63 | public Integer getCount() { 64 | return this.query().getSize(); 65 | } 66 | 67 | public Integer getPageNumber() { 68 | 69 | return this.query().getNumber(); 70 | 71 | } 72 | 73 | public Long getTotal() { 74 | return this.query().getTotalElements(); 75 | } 76 | 77 | public Object getContent() { 78 | return this.query().getContent(); 79 | } 80 | } 81 | 82 | class SexEmailType extends BasePaginationInfo implements Types { 83 | 84 | public SexEmailType(String sexName, String emailName, Pageable pageable) { 85 | 86 | super(sexName, emailName, pageable); 87 | 88 | } 89 | 90 | public Page query() { 91 | 92 | return this.instance.findBySexAndEmailContains( 93 | 94 | this.sex, 95 | 96 | this.email, 97 | 98 | this.pageable 99 | ); 100 | } 101 | 102 | public Integer getCount() { 103 | return this.query().getSize(); 104 | } 105 | 106 | public Integer getPageNumber() { 107 | 108 | return this.query().getNumber(); 109 | 110 | } 111 | 112 | public Long getTotal() { 113 | return this.query().getTotalElements(); 114 | } 115 | 116 | public Object getContent() { 117 | return this.query().getContent(); 118 | } 119 | 120 | 121 | } 122 | 123 | class SexType extends BasePaginationInfo implements Types { 124 | 125 | public SexType(String sexName, String emailName, Pageable pageable) { //String sexName, String emailName, 126 | 127 | super(sexName, emailName, pageable); 128 | } 129 | 130 | public Page query() { 131 | 132 | return this.instance.findBySex( 133 | 134 | this.sex, 135 | 136 | this.pageable 137 | ); 138 | } 139 | 140 | public Integer getCount() { 141 | return this.query().getSize(); 142 | } 143 | 144 | public Integer getPageNumber() { 145 | 146 | return this.query().getNumber(); 147 | 148 | } 149 | 150 | public Long getTotal() { 151 | return this.query().getTotalElements(); 152 | } 153 | 154 | public Object getContent() { 155 | return this.query().getContent(); 156 | } 157 | } 158 | 159 | 160 | public class PaginationFormatting { 161 | 162 | private PaginationMultiTypeValuesHelper multiValue = new PaginationMultiTypeValuesHelper(); 163 | 164 | private Map results = new HashMap<>(); 165 | 166 | public Map filterQuery(String sex, String email, Pageable pageable) { 167 | 168 | Types typeInstance; 169 | 170 | if (sex.length() == 0 && email.length() == 0) { 171 | 172 | typeInstance = new AllType(sex, email, pageable); 173 | 174 | } else if (sex.length() > 0 && email.length() > 0) { 175 | 176 | typeInstance = new SexEmailType(sex, email, pageable); 177 | 178 | } else { 179 | typeInstance = new SexType(sex, email, pageable); 180 | } 181 | 182 | this.multiValue.setCount(typeInstance.getCount()); 183 | 184 | this.multiValue.setPage(typeInstance.getPageNumber() + 1); 185 | 186 | this.multiValue.setResults(typeInstance.getContent()); 187 | 188 | this.multiValue.setTotal(typeInstance.getTotal()); 189 | 190 | this.results.put("data", this.multiValue); 191 | 192 | return results; 193 | } 194 | 195 | } -------------------------------------------------------------------------------- /src/main/java/com/example/demo/pagination/PaginationMultiTypeValuesHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.pagination; 2 | 3 | public class PaginationMultiTypeValuesHelper { 4 | 5 | private Integer count, page; 6 | 7 | private Object results; 8 | 9 | private Long total; 10 | 11 | public void setCount(Integer name) { 12 | this.count = name; 13 | } 14 | 15 | public Integer getCount() { 16 | return count; 17 | } 18 | 19 | public Integer getPage() { 20 | return page; 21 | } 22 | 23 | public void setPage(Integer page) { 24 | this.page = page; 25 | } 26 | 27 | public Object getResults() { 28 | return results; 29 | } 30 | 31 | public void setResults(Object results) { 32 | this.results = results; 33 | } 34 | 35 | public Long getTotal() { 36 | return total; 37 | } 38 | 39 | public void setTotal(Long total) { 40 | this.total = total; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/PersonsRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | import org.springframework.data.jpa.repository.JpaRepository; 8 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 9 | import org.springframework.data.jpa.repository.Query; 10 | import org.springframework.stereotype.Repository; 11 | 12 | import com.example.demo.bean.Persons; 13 | 14 | @Repository 15 | public interface PersonsRepository extends JpaRepository, JpaSpecificationExecutor { 16 | 17 | @Query(value = "select DISTINCT sex from Persons p") 18 | List findSex(); 19 | 20 | Page findAll(Pageable pageable); 21 | 22 | Page findBySexAndEmailContains(String sexName, String emailName, Pageable pageable); 23 | 24 | Page findBySex(String sexName, Pageable pageable); 25 | 26 | Persons findById(Long id); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/StudentRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 5 | import org.springframework.stereotype.Repository; 6 | 7 | import com.example.demo.bean.Student; 8 | 9 | @Repository 10 | public interface StudentRepository extends JpaRepository, JpaSpecificationExecutor { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/TreeNodeRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import com.example.demo.bean.TreeNode; 7 | 8 | @Repository 9 | public interface TreeNodeRepository extends JpaRepository{ 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.repository; 2 | 3 | import org.springframework.data.domain.Page; 4 | import org.springframework.data.domain.Pageable; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import com.example.demo.bean.User; 10 | 11 | @Repository 12 | public interface UserRepository extends JpaRepository, JpaSpecificationExecutor { 13 | 14 | Page findAll(Pageable pageable); 15 | 16 | User findById(String id); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/utils/FileUploadUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.utils; 2 | 3 | import java.io.File; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | import org.springframework.web.multipart.MultipartFile; 8 | 9 | public class FileUploadUtil { 10 | public static Boolean uploadFile(HttpServletRequest request, MultipartFile file) { 11 | System.out.println("开始"); 12 | //String path = request.getSession().getServletContext().getRealPath("upload"); 13 | String path = "C:\\Users\\shenzm\\Desktop\\upload"; 14 | String fileName = file.getOriginalFilename(); 15 | System.out.println(path); 16 | File targetFile = new File(path, fileName); 17 | if (!targetFile.exists()) { 18 | targetFile.mkdirs(); 19 | } 20 | // 保存 21 | try { 22 | file.transferTo(targetFile); 23 | return true; 24 | } catch (Exception e) { 25 | e.printStackTrace(); 26 | return false; 27 | } 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/demo/utils/HanyuPinyinHelper.java: -------------------------------------------------------------------------------- 1 | package com.example.demo.utils; 2 | 3 | import net.sourceforge.pinyin4j.PinyinHelper; 4 | import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; 5 | import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; 6 | import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; 7 | import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; 8 | import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; 9 | 10 | public class HanyuPinyinHelper { 11 | 12 | /** 13 | * 将文字转为汉语拼音 14 | * @param chineselanguage 要转成拼音的中文 15 | */ 16 | public String toHanyuPinyin(String ChineseLanguage){ 17 | char[] cl_chars = ChineseLanguage.trim().toCharArray(); 18 | String hanyupinyin = ""; 19 | HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 20 | defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写 21 | defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调 22 | defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ; 23 | try { 24 | for (int i=0; i T getBean(Class clazz) { 29 | return getApplicationContext().getBean(clazz); 30 | } 31 | 32 | public static T getBean(String name, Class clazz) { 33 | return getApplicationContext().getBean(name, clazz); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # dev env 2 | server.port=8000 3 | 4 | logging.level.root=info 5 | 6 | paginatio.max-per-page=6 7 | 8 | logging.file=classpath:/log-info.log 9 | 10 | 11 | #spring.mvc.view.prefix=/ 12 | #spring.mvc.view.suffix=.html 13 | 14 | 15 | # datasource 16 | spring.jpa.generate-ddl=true 17 | spring.jpa.hibernate.ddl-auto=update 18 | spring.datasource.continueOnError=true 19 | spring.jpa.hibernate.naming.strategy=org.hibernate.cfg.ImprovedNamingStrategy 20 | spring.jpa.database=mysql 21 | spring.jpa.show-sql=true 22 | 23 | spring.datasource.url=jdbc:mysql://10.1.51.96:3306/test?useUnicode=true&characterEncoding=UTF-8&connectTimeout=60000&socketTimeout=60000&autoReconnect=true&autoReconnectForPools=true&failOverReadOnly=false 24 | spring.datasource.username=root 25 | spring.datasource.password=root 26 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 27 | spring.datasource.sqlScriptEncoding=utf-8 28 | 29 | # HikariCP settings 30 | spring.datasource.hikari.connection-timeout=60000 31 | spring.datasource.hikari.maximum-pool-size=15 32 | spring.datasource.hikari.max-lifetime=1800000 33 | spring.datasource.hikari.idle-timeout=600000 34 | spring.datasource.hikari.read-only=false 35 | 36 | #dataSoruce config 37 | spring.datasource.max-active=100 38 | spring.datasource.max-idle=8 39 | spring.datasource.min-idle=8 40 | spring.datasource.initial-size=30 41 | spring.datasource.validation-query=select 1 42 | spring.datasource.test-on-borrow=true 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/resources/static/chart-backup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | D3制作力导向关系图 6 | 7 | 8 |

9 | 10 | 11 | 152 | 153 | -------------------------------------------------------------------------------- /src/main/resources/static/chart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | D3制作力导向关系图 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/static/chart.js: -------------------------------------------------------------------------------- 1 | /** 2 | * nodes : 3 | * name:节点的title, 4 | * group:围绕中心的层数,一个组合同一个颜色 5 | * index:区分的标记 6 | * 7 | * links: 8 | * source:源 9 | * target:链接的目的地 10 | */ 11 | $(document).ready(function () { 12 | var renderId ="#main_2"; 13 | 14 | var jsonStr = { 15 | "nodes": [ 16 | {"name": "中国", "group": 1, "index": 0}, 17 | {"name": "内蒙古", "group": 2, "index": 1}, 18 | {"name": "猫咪", "group": 3, "index": 2}, 19 | {"name": "四川", "group": 2, "index": 3}, 20 | {"name": "棕熊", "group": 2, "index": 4}, 21 | {"name": "臭豆腐", "group": 3, "index": 5}, 22 | {"name": "小猪猪", "group": 2, "index": 6}, 23 | {"name": "湖南", "group": 2, "index": 7}, 24 | {"name": "大熊猫", "group": 3, "index": 8}, 25 | {"name": "北京", "group": 2, "index": 9}, 26 | {"name": "雾霾", "group": 3, "index": 10} 27 | ], 28 | "links": [ 29 | {"source": 0, "target": 1}, 30 | {"source": 1, "target": 2}, 31 | {"source": 0, "target": 3}, 32 | {"source": 3, "target": 8}, 33 | {"source": 0, "target": 4}, 34 | {"source": 0, "target": 6}, 35 | {"source": 0, "target": 7}, 36 | {"source": 7, "target": 5}, 37 | {"source": 0, "target": 9}, 38 | {"source": 9, "target": 10} 39 | ] 40 | }; 41 | 42 | drawChart(renderId,jsonStr);/*在$(“#main_2”)作用域内画图*/ 43 | 44 | }); 45 | 46 | /** 47 | * 48 | * @param renderId 渲染的ID 49 | * @param graph 数据 50 | * @returns 51 | */ 52 | function drawChart(renderId, graph) { 53 | var index = 0; 54 | var width = 660, height = 580; 55 | var color = ["#FF8000", "#9393FF", "#0080FF"]; 56 | var force = d3.layout.force() /*layout将json格式转化为力学图可用的格式*/ 57 | .linkDistance(20) /*指定结点连接线的距离,默认为20*/ 58 | .charge(-300) /*顶点的电荷数。该参数决定是排斥还是吸引,数值越小越互相排斥*/ 59 | .size([width, height]); /*作用域*/ 60 | var svg; 61 | var dd = $('
'); 62 | $(renderId).append(dd); 63 | /*D3采用SVG来更加生动展现数据,此处设置svg的基本样式*/ 64 | svg = d3.select(".d3strench").append("svg") 65 | .attr("width", width) 66 | .attr("height", height) 67 | .attr('border', 'red') 68 | .style({ 69 | 'margin': '0 auto', 70 | 'display': 'block' 71 | }); 72 | var nodes = graph.nodes.slice(), /*nodes() 里传入顶点的数组*/ links = [], bilinks = []; 73 | 74 | 75 | /*将数据组装成source-->target的形式*/ 76 | graph.links.forEach(function (link) { 77 | var s = nodes[link.source], 78 | t = nodes[link.target], 79 | i = {}; // 中间节点 80 | nodes.push(i); 81 | links.push({source: s, target: i}, {source: i, target: t}); 82 | bilinks.push([s, i, t]); 83 | }); 84 | force.nodes(nodes).links(links).start(); 85 | 86 | /*svg的path标签被称为”可以组成任何形状的形状”,所以此处用path标签来绘制线条*/ 87 | var link = svg.selectAll(".link")//线条 88 | .data(bilinks) 89 | .enter().append("path") 90 | .attr("class", "link") 91 | .attr("stroke", function (d) { 92 | return color[d[0].group - 1]; 93 | }).attr("stroke-width", 1) 94 | 95 | /*接下来是数据的渲染*/ 96 | var node = svg.selectAll(".node") 97 | .data(graph.nodes) 98 | .enter().append("g") 99 | .attr("class", "node") 100 | .attr("group", function (d) { 101 | return d.group; 102 | }).call(force.drag); 103 | 104 | node.append("circle") 105 | .attr("r", 8) 106 | .style("fill", function (d) { 107 | return color[d.group - 1]; 108 | }) 109 | .style("stroke", function (d) { 110 | return color[d.group - 1]; 111 | }).style("stroke-width", "8") //圆外面的轮廓线 112 | .style("stroke-opacity", "0.6"); //圆外面的轮廓线的透明度 113 | 114 | node.filter(function (d) { 115 | return d.group !== 0; 116 | }).append("text") 117 | .attr("font-family", "微软雅黑") 118 | .attr("text-anchor", "middle") 119 | .attr("dy", function () { //dy表示文字的偏移量 120 | return "0em"; 121 | }) 122 | .attr('x', function (d) { 123 | d3.select(this).append('tspan')//添加文字 124 | .text(function () { 125 | return d.name; 126 | }); 127 | d3.selectAll(".node[group='3'] text")//设置圆圈的样式以及半径 128 | .selectAll("tspan") 129 | .attr("fill", "#000"); 130 | d3.selectAll(".node[group='1'] circle") 131 | .attr('r', 40) 132 | .style('cursor', 'pointer'); 133 | d3.selectAll(".node[group='2'] circle") 134 | .attr('r', 25); 135 | d3.selectAll(".node[group='3'] circle") 136 | .attr('r', 30); 137 | }); 138 | 139 | 140 | //为每个节点设置title(类似于html标签的title属性) 141 | node.append("title").text(function (d) {return d.name;}); 142 | 143 | /*拖拽事件*/ 144 | force.on("tick", function () { 145 | link.attr("d", function (d) {//设置线条的偏移以及路径 146 | var dx = d[2].x - d[0].x, dy = d[2].y - d[0].y, dr = Math.sqrt(dx * dx + dy * dy); 147 | /*下面表示位置的菜蔬中, M(表示画笔落下的位置), A(画椭圆)是大写的,表示绝对位置。当使用相对位置时,要小写*/ 148 | return "M" + d[0].x + "," + d[0].y + "A" + dr + "," + dr + " 0 0,0 " + d[2].x + "," + d[2].y; 149 | }).attr("fill", "transparent"); 150 | node.attr("transform", function (d) {//circle节点的偏移量 151 | return "translate(" + d.x + "," + d.y + ")"; 152 | }); 153 | }); 154 | force.stop(); 155 | force.start(); 156 | } -------------------------------------------------------------------------------- /src/main/resources/static/force.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 力导向图 5 | 6 | 7 | 11 | 12 | 13 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/test/java/com/example/demo/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.demo; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------