前言:经过博文(1)vue搭建,(2)ssm搭建,到这里就该真真切切的实现小功能了<-_->

  规划:实现登录,用户列表查询,访问日志aop;

  开始先解决跨域:在目录config/index.js配置

 1 'use strict'
 2 // Template version: 1.3.1
 3 // see http://vuejs-templates.github.io/webpack for documentation.
 4 
 5 const path = require('path')
 6 
 7 module.exports = {
 8   dev: {
 9 
10     // Paths
11     assetsSubDirectory: 'static',
12     assetsPublicPath: '/',
13     /*
14     '/api' 为匹配项,target 为被请求的后台地址
15     changeOrigin设置为true,那么本地会虚拟一个服务端接收你的请求并代你发送该请求,这样就不会有跨域问题了,只适用于开发环境.如果上线的话,可以考虑nginx
16     pathRewrite 是用来重写地址,将前缀 '/api' 转为 '/',如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉,或者你可以自定义一个公共接口匹配地址
17     如:请求http://127.0.0.1:8080/user/queryUserList,就可以写成:/api/user/queryUserList
18     */
19     proxyTable: {
20       '/api':{
21         target:'http://127.0.0.1:8080',
22         changeOrigin:true,
23         pathRewrite:{
24           '^/api':'/'
25         }
26       }
27     },
28 
29     // Various Dev Server settings
30     host: 'localhost', // can be overwritten by process.env.HOST
31     port: 6666, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
32     autoOpenBrowser: false,
33     errorOverlay: true,
34     notifyOnErrors: true,
35     poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
36 
37 
38     /**
39      * Source Maps
40      */
41 
42     // https://webpack.js.org/configuration/devtool/#development
43     devtool: 'cheap-module-eval-source-map',
44 
45     // If you have problems debugging vue-files in devtools,
46     // set this to false - it *may* help
47     // https://vue-loader.vuejs.org/en/options.html#cachebusting
48     cacheBusting: true,
49 
50     cssSourceMap: true
51   },
52 
53   build: {
54     // Template for index.html
55     index: path.resolve(__dirname, '../dist/index.html'),
56 
57     // Paths
58     assetsRoot: path.resolve(__dirname, '../dist'),
59     assetsSubDirectory: 'static',
60     assetsPublicPath: '/',
61 
62     /**
63      * Source Maps
64      */
65 
66     productionSourceMap: true,
67     // https://webpack.js.org/configuration/devtool/#production
68     devtool: '#source-map',
69 
70     // Gzip off by default as many popular static hosts such as
71     // Surge or Netlify already gzip all static assets for you.
72     // Before setting to `true`, make sure to:
73     // npm install --save-dev compression-webpack-plugin
74     productionGzip: false,
75     productionGzipExtensions: ['js', 'css'],
76 
77     // Run the build command with an extra argument to
78     // View the bundle analyzer report after build finishes:
79     // `npm run build --report`
80     // Set to `true` or `false` to always turn it on or off
81     bundleAnalyzerReport: process.env.npm_config_report
82   }
83 }
config/index.js

   日志sql脚本

 1 /*
 2  Navicat Premium Data Transfer
 3 
 4  Source Server         : ssm
 5  Source Server Type    : MySQL
 6  Source Server Version : 80011
 7  Source Host           : localhost:3306
 8  Source Schema         : ssm
 9 
10  Target Server Type    : MySQL
11  Target Server Version : 80011
12  File Encoding         : 65001
13 
14  Date: 05/08/2019 16:44:14
15 */
16 
17 SET NAMES utf8mb4;
18 SET FOREIGN_KEY_CHECKS = 0;
19 
20 -- ----------------------------
21 -- Table structure for tbsyslog
22 -- ----------------------------
23 DROP TABLE IF EXISTS `tbsyslog`;
24 CREATE TABLE `tbsyslog`  (
25   `id` int(11) NOT NULL AUTO_INCREMENT,
26   `logId` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
27   `accessDate` datetime(0) NULL DEFAULT NULL,
28   `requestType` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
29   `accessInterface` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
30   `interfaceParams` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
31   `accessSource` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
32   `accessIp` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
33   `executeTime` int(11) NULL DEFAULT NULL,
34   PRIMARY KEY (`id`) USING BTREE
35 ) ENGINE = InnoDB AUTO_INCREMENT = 761 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
36 
37 SET FOREIGN_KEY_CHECKS = 1;
tbSysLog.sql

 

                  前端项目结构图                                        后端项目结构图

     

一、前端

  1、安装axios     cnpm install axios -S

  2、在config/dev.env.js里添加  BASE_URL:'"/api"'  (因为这里在3里要引用,也可不配置,你在3里写死就行

  3、封装axios

 1 import axios from 'axios' //引入axios
 2 
 3 /* 创建axios实例 */
 4 const service = axios.create({
 5   //这个process.env.BASE_URL在config/dev.evn.js、prod.evn.js里面进行配置
 6   baseURL: process.env.BASE_URL, // api的base_url
 7   timeout: 5000 // 请求超时时间
 8 });
 9 
10 /*response拦截器,进行错误处理*/
11 service.interceptors.response.use(response => {
12     return response;
13   },
14   error => {
15     // 失败处理
16     switch (error.response.status) {
17       case 400:
18         error.message = '错误请求'
19         break;
20       case 401:
21         error.message = '未授权,请重新登录'
22         break;
23       case 403:
24         error.message = '拒绝访问'
25         break;
26       case 404:
27         error.message = '请求错误,未找到该资源'
28         break;
29       case 405:
30         error.message = '请求方法未允许'
31         break;
32       case 408:
33         error.message = '请求超时'
34         break;
35       case 500:
36         error.message = '服务器端出错'
37         break;
38       case 501:
39         error.message = '网络未实现'
40         break;
41       case 502:
42         error.message = '网络错误'
43         break;
44       case 503:
45         error.message = '服务不可用'
46         break;
47       case 504:
48         error.message = '网络超时'
49         break;
50       case 505:
51         error.message = 'http版本不支持该请求'
52         break;
53       default:
54         error.message = `连接错误${error.response.status}`
55     }
56     return Promise.reject(error);
57   }
58 );
59 
60 /*reuqest拦截器*/
61 service.interceptors.request.use(config => {
62     return config;
63   },
64   error => {
65     return Promise.reject(error);
66   }
67 );
68 
69 export default service;
utils/request.js

  4、封装一个公共的axios请求API

 1 import request from '@/utils/request'
 2 
 3 export function commonAPI(api,postData){
 4   if(postData===''){
 5     return request({
 6       url:'/'+api,
 7       method:'post'
 8     })
 9   }else{
10     return request({
11       url:'/'+api,
12       method:'post',
13       data:postData
14     })
15   }
16 }
api/commonAPI.js

     5、封装一个日期格式转化的api

 1 /**
 2  * 格式为yyyy-MM-dd OR yyyy-MM-dd HH:mm:ss
 3  * @param {Object} date   日期对象
 4  * @param {Object} hasTime 是否有时间  true有时间,false没有时间
 5  */
 6 export function formatDate(date,hasTime){
 7     var hasTime = hasTime;//可传第二个参数false,返回yyyy-MM-dd
 8     var d = date;
 9     var year = d.getFullYear();
10     var month = (d.getMonth()+1)<10 ? '0'+(d.getMonth()+1) : (d.getMonth()+1);
11     var day = d.getDate()<10 ? '0'+d.getDate() : d.getDate();
12     var hour = d.getHours()<10 ? '0'+d.getHours() : d.getHours();
13     var minute = d.getMinutes()<10 ? '0'+d.getMinutes() : d.getMinutes();
14     var second = d.getSeconds()<10 ? '0'+d.getSeconds() : d.getSeconds();
15     if(hasTime){
16         return [year, month, day].join('-') + " " + [hour, minute, second].join(':');
17     }else{
18         return [year, month, day].join('-');
19     }
20 }
utils/index.js

  6、vue文件

  1 <template>
  2   <div class="box">
  3     <div id="login" style="width: 320px;height: 300px;text-align: center;">
  4       <el-form :model="loginForm" ref="loginForm" :rules="rules">
  5         <el-form-item>
  6           <span style="color: white;font-family: 楷体;font-size: 26px;">&nbsp;&nbsp;&nbsp;&nbsp;</span>
  7         </el-form-item>
  8         <el-form-item prop="userName">
  9           <el-input type="text" v-model="loginForm.userName" placeholder="用户名">
 10             <template slot="prepend"><i class="el-icon-user" style="font-size: 20px; color: white;"></i></template>
 11           </el-input>
 12         </el-form-item>
 13         <el-form-item prop="password">
 14           <el-input type="text" v-model="loginForm.password" placeholder="密码" show-password>
 15             <template slot="prepend"><i class="el-icon-lock" style="font-size: 20px;color: white;"></i></template>
 16           </el-input>
 17         </el-form-item>
 18         <el-form-item>
 19           <el-button type="primary" size="medium" :loading="loading" style="font-size: 20px;font-family: 微软雅黑;width: 320px;"
 20             @click="clickLogin">&nbsp;&nbsp;&nbsp;</el-button>
 21         </el-form-item>
 22       </el-form>
 23     </div>
 24   </div>
 25 </template>
 26 
 27 <script>
 28   import {
 29     commonAPI
 30   } from '@/api/commonAPI';
 31   export default {
 32     data() {
 33       var validateUserName = (rule, value, callback) => {
 34         if (value.length === 0) {
 35           return callback(new Error('请输入用户名'))
 36         } else {
 37           callback()
 38         }
 39       }
 40       var validatePassword = (rule, value, callback) => {
 41         if (value.length === 0) {
 42           callback(new Error('请输入密码'))
 43         } else if (value.length < 3) {
 44           callback(new Error('密码不能小于3位'))
 45         } else {
 46           callback()
 47         }
 48       }
 49       return {
 50         loginForm: {
 51           userName: '',
 52           password: ''
 53         },
 54         loading: false, //登陆加载效果
 55         rules: {
 56           userName: [{
 57             required: true,
 58             trigger: 'blur',
 59             validator: validateUserName
 60           }],
 61           password: [{
 62             required: true,
 63             trigger: 'blur',
 64             validator: validatePassword
 65           }]
 66         }
 67       }
 68     },
 69     methods: {
 70       clickLogin() {
 71         this.$refs.loginForm.validate(valid => {
 72           if (valid) {//校验成功
 73             this.loading = true
 74             setTimeout(() => {//为了看到登录转圈圈的加载效果,这里来一个延迟2秒发送请求
 75               //封装的公共请求API
 76               commonAPI('queryUser', this.loginForm).then(res => {
 77                 let data = res.data;
 78                 if (data.info.code === '0' && data.data === 'OK') {
 79                   this.$router.push({
 80                     name: 'layoutYHGL'
 81                   });
 82                 } else {
 83                   this.$notify({
 84                     title: '登录提示',
 85                     message: '用户名或密码错误',
 86                     position: 'bottom-right',
 87                     type: 'error'
 88                   });
 89                   this.loading = false;
 90                 }
 91               }).catch(error=>{
 92                 this.loading = false;
 93                 this.$notify({//这里采用element ui的一个错误显示效果模板
 94                   title: '登录提示',
 95                   message: error.message,
 96                   position: 'bottom-right',
 97                   type: 'error'
 98                 });
 99               })
100             }, 2000);
101           } else {
102             return false;
103           }
104         })
105       }
106     }
107   }
108 </script>
109 
110 <style scoped="scoped">
111   .box {
112     display: flex;
113     height: 100%;
114     justify-content: center;
115     align-items: center;
116   }
117 </style>
118 <style>
119   .el-input-group__prepend {
120     padding: 0px 15px;
121     background-color: #CCCCCC;
122     border: 1 solid #72767B;
123   }
124 
125   body {
126     background-color: #72767B;
127     margin: 0px;
128   }
129 </style>
login/Login.vue
  1 <template>
  2   <el-container>
  3     <el-header style="background-color:white">
  4       <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini">
  5         <el-form-item label="访问时间">
  6           <el-date-picker class="dateStyle" v-model="formInline.beginTime" value-format="yyyy-MM-dd HH:mm:ss" @change="dataFormat" type="datetime" placeholder="选择日期时间"></el-date-picker>
  7&nbsp;<el-date-picker class="dateStyle" v-model="formInline.endTime" value-format="yyyy-MM-dd HH:mm:ss" @change="dataFormat" type="datetime" placeholder="选择日期时间"></el-date-picker>
  8         </el-form-item>
  9         <el-form-item>
 10           <el-button type="primary" class="btn" @click="onSubmit"><i class="el-icon-search"></i>查询</el-button>
 11         </el-form-item>
 12         <el-form-item>
 13           <el-button type="danger" class="btn" @click="resetting"><i class="el-icon-refresh"></i>重置</el-button>
 14         </el-form-item>
 15       </el-form>
 16     </el-header>
 17     <el-main class="elMain">
 18       <el-table v-loading="loading" :data="tableData" height="100%" stripe border size="mini">
 19         <el-table-column align="center" label="访问时间" prop="accessDate" width="140"></el-table-column>
 20         <el-table-column align="center" label="请求方式" prop="requestType" width="90"></el-table-column>
 21         <el-table-column align="center" label="请求接口" prop="accessInterface" width="280"></el-table-column>
 22         <el-table-column header-align="center" align="left" label="接口参数" width="90">
 23           <template slot-scope="scope" v-if="scope.row.interfaceParams">
 24             <el-popover v-if="scope.row.interfaceParams.length>10" placement="left-end" width="200" trigger="hover"
 25               :content="scope.row.interfaceParams">
 26               <span slot="reference" style="text-overflow: ellipsis;white-space:nowrap;overflow: hidden;">{{scope.row.interfaceParams}}</span>
 27             </el-popover>
 28             <span v-else>{{scope.row.interfaceParams}}</span>
 29           </template>
 30         </el-table-column>
 31         <el-table-column align="center" label="访问来源" prop="accessSource" width="263"></el-table-column>
 32         <el-table-column align="center" label="访问IP" prop="accessIp" width="130"></el-table-column>
 33         <el-table-column align="center" label="执行时长" prop="executeTime" width="90"></el-table-column>
 34       </el-table>
 35     </el-main>
 36     <el-footer>
 37       <div style="padding: 15px 0;text-align: right;">
 38         <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="formInline.pageNum"
 39           :page-sizes="pageSizes" :page-size="formInline.pageSize" layout="total, sizes, prev, pager, next, jumper"
 40           :total="pageTotal">
 41         </el-pagination>
 42       </div>
 43     </el-footer>
 44 
 45   </el-container>
 46 </template>
 47 
 48 <script>
 49   import {formatDate} from '@/utils/index';
 50   import {commonAPI} from '@/api/commonAPI';
 51   export default {
 52     data() {
 53       return {
 54         tableData: [],
 55         loading: false,
 56         formInline: {
 57           pageNum: 1,
 58           pageSize: 10,
 59           beginTime: new Date(new Date().getTime()-3600*1000*24*7),
 60           endTime: new Date()
 61         },
 62         pageSizes: [5, 10, 15, 20],
 63         pageTotal: 0
 64       }
 65     },
 66     created() {
 67       this.formInline.beginTime=formatDate(this.formInline.beginTime,true);
 68       this.formInline.endTime=formatDate(this.formInline.endTime,true);
 69       this.getData();
 70     },
 71     methods: {
 72       getData() {
 73         this.loading = true,
 74           commonAPI('sysLogList',this.formInline)
 75           .then(res => {
 76             this.loading = false;
 77             this.tableData = res.data.data.rows;
 78             this.pageTotal = res.data.data.total;
 79           })
 80       },
 81       dataFormat(val){
 82         console.log(val);
 83       },
 84       onSubmit() {//查询
 85         this.getData();
 86       },
 87       resetting() {//重置
 88         this.formInline.beginTime=formatDate(new Date(new Date().getTime()-3600*1000*24*7),true);
 89         this.formInline.endTime=formatDate(new Date(),true);
 90         this.getData();
 91       },
 92       handleSizeChange(val) {
 93         //console.log(`每页 ${val} 条`);
 94         this.formInline.pageSize = val;
 95         this.formInline.pageNum = 1;
 96         this.getData();
 97       },
 98       handleCurrentChange(val) {
 99         //console.log(`当前页: ${val}`);
100         this.formInline.pageNum = val;
101         this.getData();
102       }
103     }
104   }
105 </script>
106 
107 <style scoped>
108   .dateStyle,.btn {
109     margin-top: 18px;
110   }
111 
112   .elMain {
113     height: 418px;
114   }
115 </style>
116 <style>
117   .el-main {
118     padding: 5px 10px;
119   }
120 
121   .el-table th {
122     height: 45px;
123     font-size: 16px;
124     font-family: 微软雅黑;
125     font-weight: 500;
126     color: darkblue;
127   }
128 
129   body {
130     margin: 0px;
131   }
132 </style>
sys/SysLogList.vue
  1 <template>
  2     <el-container>
  3     <el-header style="background-color:white">
  4       <el-form :inline="true" :model="formInline" class="demo-form-inline" size="mini">
  5         <el-form-item label="用户名">
  6           <el-input v-model="formInline.userName" placeholder="用户名" class="elInput"></el-input>
  7         </el-form-item>
  8         <el-form-item label="性别">
  9           <el-select v-model="formInline.sex" class="elInput">
 10             <el-option label="全部" value=""></el-option>
 11             <el-option label="男" value="0"></el-option>
 12             <el-option label="女" value="1"></el-option>
 13           </el-select>
 14         </el-form-item>
 15         <el-form-item>
 16           <el-button type="primary" class="btn" @click="onSubmit"><i class="el-icon-search"></i>查询</el-button>
 17         </el-form-item>
 18         <el-form-item>
 19           <el-button type="danger" class="btn" @click="resetting"><i class="el-icon-refresh"></i>重置</el-button>
 20         </el-form-item>
 21       </el-form>
 22     </el-header>
 23     <el-main class="elMain">
 24       <el-table v-loading="loading" :data="tableData" height="100%" stripe border size="mini">
 25         <el-table-column align="center" label="编号" prop="uid"></el-table-column>
 26         <el-table-column align="center" label="用户名" prop="userName"></el-table-column>
 27         <el-table-column align="center" label="姓名" prop="uName"></el-table-column>
 28         <el-table-column align="center" label="年龄" prop="age"></el-table-column>
 29         <el-table-column align="center" label="性别">
 30           <template slot-scope="scope">
 31             <span v-if="scope.row.sex===0"></span>
 32             <span v-if="scope.row.sex===1"></span>
 33           </template>
 34         </el-table-column>
 35       </el-table>
 36     </el-main>
 37     <el-footer>
 38       <div style="padding: 15px 0;text-align: right;">
 39         <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="formInline.pageNum"
 40           :page-sizes="pageSizes" :page-size="formInline.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
 41         </el-pagination>
 42       </div>
 43     </el-footer>
 44   </el-container>
 45 </template>
 46 
 47 <script>
 48   import {commonAPI} from '@/api/commonAPI'
 49   export default {
 50     data() {
 51       return {
 52         tableData: [],
 53         loading: false,
 54         formInline: {
 55           userName: '',
 56           sex: '',
 57           pageNum:1,
 58           pageSize:10
 59         },
 60         pageSizes:[5, 10, 15, 20],
 61         pageTotal:0
 62       }
 63     },
 64     created() {
 65       this.getData();
 66     },
 67     methods: {
 68       getData() {
 69         this.loading = true,
 70           commonAPI('queryUserList',this.formInline)
 71           .then(res => {
 72             this.loading = false;
 73             this.tableData = res.data.data.rows;
 74             this.pageTotal=res.data.data.total;
 75           })
 76       },
 77       onSubmit() {
 78         this.getData();
 79       },
 80       resetting() {
 81         this.formInline.userName = '';
 82         this.formInline.sex = '';
 83         this.getData();
 84       },
 85       handleSizeChange(val) {
 86         //console.log(`每页 ${val} 条`);
 87         this.formInline.pageSize=val;
 88         this.formInline.pageNum=1;
 89         this.getData();
 90       },
 91       handleCurrentChange(val) {
 92         //console.log(`当前页: ${val}`);
 93         this.formInline.pageNum=val;
 94         this.getData();
 95       }
 96     }
 97   }
 98 </script>
 99 
100 <style scoped>
101   .elInput,
102   .btn {
103     margin-top: 18px;
104   }
105 </style>
106 <style>
107   .el-main {
108     padding: 5px 10px;
109   }
110   .elMain{
111     height: 418px;
112   }
113   .el-table th {
114     height: 45px;
115     font-size: 16px;
116     font-family: 微软雅黑;
117     font-weight: 500;
118     color: darkblue;
119   }
120 </style>
user/UserList.vue

 二、后端(按上面结构图,从上往下

 1 package com.wzz.aspect;
 2 
 3 import com.wzz.common.IDUtil;
 4 import com.wzz.common.StringUtil;
 5 import com.wzz.controller.SysAccessLogController;
 6 import com.wzz.service.ISysAccessLogService;
 7 import org.aspectj.lang.JoinPoint;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Component;
10 
11 import javax.servlet.http.HttpServletRequest;
12 import java.util.Arrays;
13 import java.util.Date;
14 import java.util.HashMap;
15 import java.util.Map;
16 
17 /**
18  * @ClassName SysAccessLogAspect
19  * @Description TODO 系统访问日志切面类
20  * @Author AZhen
21  * Version 1.0
22  **/
23 @Component
24 public class SysAccessLogAspect {
25 
26     @Autowired
27     private HttpServletRequest request;
28     @Autowired
29     private ISysAccessLogService sysAccessLogService;
30     //访问时间
31     private Date accessDate;
32     //日志信息Map
33     private Map<String,Object> logMap=new HashMap<>();
34 
35     private Class clazz;  //访问类
36 
37     public void doBefore(JoinPoint jp){
38         clazz = jp.getTarget().getClass();
39         if (clazz!= SysAccessLogController.class) {
40             //日志ID
41             logMap.put("logId", IDUtil.getUUID());
42 
43             String url = request.getRequestURL().toString();
44             //请求url
45             logMap.put("accessInterface", url);
46 
47             String ip = request.getRemoteAddr();
48             //请求Ip
49             logMap.put("accessIp", ip);
50 
51             String requestType = request.getMethod();
52             //请求方式
53             logMap.put("requestType", requestType);
54 
55             accessDate = new Date();
56             //访问时间
57             logMap.put("accessDate", accessDate);
58 
59             String args = Arrays.toString(jp.getArgs());
60             //方法参数
61             logMap.put("interfaceParams", args);
62 
63             String browserSystemInfo = StringUtil.getBrowserSystemInfo(request);
64             //访问浏览器系统信息
65             logMap.put("accessSource", browserSystemInfo);
66         }
67     }
68 
69     public void doAfter(JoinPoint jp){
70         if (clazz!=SysAccessLogController.class){
71             long executeTime = new Date().getTime() - accessDate.getTime();
72             //执行时长
73             logMap.put("executeTime",executeTime);
74             //插入日志信息
75             sysAccessLogService.saveSysLog(logMap);
76         }
77     }
78 }
SysAccessLogAspect.java
 1 package com.wzz.common;
 2 
 3 import com.wzz.model.InfoMsg;
 4 import com.wzz.model.ResponseBody;
 5 
 6 /**
 7  * @ClassName AssembleResponseMsg
 8  * @Description TODO  封装ResponseBody内容
 9  * @Author AZhen
10  * Version 1.0
11  **/
12 public class AssembleResponseMsg {
13 
14     /**
15      * 成功返回内容
16      * @Author AZhen
17      * @Param [data]
18      * @return com.wzz.model.ResponseBody
19      **/
20     public <T>ResponseBody success(T data){
21         ResponseBody<T> resp=new ResponseBody<T>();
22         resp.setData(data);
23         InfoMsg info=new InfoMsg();
24         resp.setInfo(info);
25         return resp;
26     }
27 
28     /**
29      * 失败/异常返回内容
30      * @Author AZhen
31      * @Param [status, errorCode, message]
32      * @return com.wzz.model.ResponseBody
33      **/
34     public <T>ResponseBody failure(int status,String errorCode,String message){
35         ResponseBody<T> resp=new ResponseBody<T>();
36         resp.setStatus(status);
37         InfoMsg info=new InfoMsg();
38         info.setCode(errorCode);
39         info.setMessage(message);
40         resp.setInfo(info);
41         return resp;
42     }
43 }
AssembleResponseMsg.java
 1 package com.wzz.common;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 
 6 /**
 7  * @ClassName DateUtils
 8  * @Description TODO  日期工具类
 9  * @Author AZhen
10  * Version 1.0
11  **/
12 public class DateUtil {
13 
14     /**
15      * 返回字符串形式的当前日期
16      * @Author AZhen
17      * @Param [pattern]  模板参数  如:"yyyy-MM-dd"
18      * @return java.lang.String
19      **/
20     public static String getCurrentDateStr(String pattern){
21         SimpleDateFormat format=new SimpleDateFormat(pattern);
22         String currentDateStr = format.format(new Date());
23         return currentDateStr;
24     }
25 }
DateUtil.java
 1 package com.wzz.common;
 2 
 3 import java.util.UUID;
 4 
 5 /**
 6  * 各种ID工具类
 7  * @ClassName IDUtil
 8  * @Description TODO
 9  * @Author AZhen
10  * Version 1.0
11  **/
12 public class IDUtil {
13 
14     /**
15      * 获取uuid(以去掉'-'字符)
16      * @Author AZhen
17      * @Param []
18      * @return java.lang.String
19      **/
20     public static String getUUID(){
21         return UUID.randomUUID().toString().replace("-", "");
22     }
23 }
IDUtil.java
 1 package com.wzz.common;
 2 
 3 import eu.bitwalker.useragentutils.UserAgent;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 
 7 /**
 8  * 字符串工具类
 9  * @ClassName StringUtil
10  * @Description TODO
11  * @Author AZhen
12  * Version 1.0
13  **/
14 public class StringUtil {
15 
16     /**
17      * 浏览器和系统信息
18      * @Author AZhen
19      * @Param [request]
20      * @return java.lang.String
21      **/
22     public static String getBrowserSystemInfo(HttpServletRequest request){
23         UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
24         String BSInfo = userAgent.getOperatingSystem() + "-" + userAgent.getBrowser() + "(" + userAgent.getBrowserVersion() + ")";
25         return BSInfo;
26     }
27 
28 }
StringUtil.java
 1 package com.wzz.controller;
 2 
 3 import com.wzz.common.AssembleResponseMsg;
 4 import com.wzz.model.ResponseBody;
 5 import com.wzz.service.ISysAccessLogService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.web.bind.annotation.RequestBody;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import java.util.Map;
12 
13 /**
14  * 系统访问日志Controller
15  * @ClassName SysAccessLogController
16  * @Description TODO
17  * @Author AZhen
18  * Version 1.0
19  **/
20 @RestController
21 public class SysAccessLogController {
22     @Autowired
23     private ISysAccessLogService sysAccessLogService;
24 
25     /**
26      * 查询系统访问日志列表
27      * @Author AZhen
28      * @Param [map]
29      * @return com.wzz.model.ResponseInfo
30      **/
31     @RequestMapping(value = "/sysLogList",produces = "application/json;charset=utf-8")
32     public ResponseBody querySysLogList(@RequestBody Map<String,Object> map){
33         Map<String, Object> resultMap = sysAccessLogService.querySysLogList(map);
34         return new AssembleResponseMsg().success(resultMap);
35     }
36 }
SysAccessLogController.java
 1 package com.wzz.controller;
 2 
 3 import com.wzz.common.AssembleResponseMsg;
 4 import com.wzz.model.ResponseBody;
 5 import com.wzz.service.IUserService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.web.bind.annotation.RequestBody;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RestController;
10 
11 import java.util.Map;
12 
13 /**
14  * @ClassName UserController
15  * @Description TODO 用户控制层
16  * @Author AZhen
17  * Version 1.0
18  **/
19 @RestController
20 public class UserController {
21     @Autowired
22     private IUserService userService;
23 
24     @RequestMapping(value = "/queryUserList",produces = "application/json;charset=utf-8")
25     public ResponseBody queryUserList(@RequestBody Map<String,Object> map){
26         Map<String, Object> resultMap = userService.queryUserList(map);
27         return new AssembleResponseMsg().success(resultMap);
28     }
29     @RequestMapping(value = "/queryUser",produces = "application/json;charset=utf-8")
30     public ResponseBody queryUser(@RequestBody Map<String,Object> map){
31         int flag = userService.queryUser(map);
32         if (flag==1){
33             return new AssembleResponseMsg().success("OK");
34         }{
35             return new AssembleResponseMsg().failure(200,"error","用户名或密码错误");
36         }
37     }
38 
39 }
UserController.java
SysAccessLogMapper.java
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.wzz.mapper.SysAccessLogMapper">
 6     <select id="querySysLogList" parameterType="map" resultType="hashMap">
 7         SELECT DATE_FORMAT(t.accessDate,'%Y-%m-%d %H:%i:%s') accessDate,t.requestType,t.accessInterface,t.interfaceParams,t.accessSource,t.accessIp,t.executeTime FROM tbsyslog t where t.accessDate&gt;=#{beginTime} and t.accessDate&lt;=#{endTime} order by t.accessDate DESC
 8     </select>
 9     <insert id="saveSysLog" parameterType="map">
10         insert into  tbSysLog(logId,accessDate,requestType,accessInterface,interfaceParams,accessSource,accessIp,executeTime)
11          values (#{logId},#{accessDate},#{requestType},#{accessInterface},#{interfaceParams},#{accessSource},#{accessIp},#{executeTime})
12     </insert>
13 </mapper>
SysAccessLogMapper.xml
 1 package com.wzz.mapper;
 2 
 3 import com.wzz.model.User;
 4 
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 /**
 9  * @ClassName UserMapper
10  * @Description TODO 用户持久层接口
11  * @Author AZhen
12  * Version 1.0
13  **/
14 public interface UserMapper {
15     List<User> queryUserList(Map<String, Object> map);
16 
17     //查询用户
18     int queryUser(Map<String, Object> map);
19 }
UserMapper.java
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.wzz.mapper.UserMapper">
 6     <!--因为在sqlMapConfig.xml中配置了别名,所以直接写user就可以-->
 7     <select id="queryUserList" parameterType="map" resultType="user">
 8         select * from tbUser
 9         <where>
10             <if test="userName!=null and userName!=''">
11                 userName like CONCAT('%',#{userName},'%')
12             </if>
13             <if test="sex!=null and sex!=''">
14                 AND sex=#{sex}
15             </if>
16         </where>
17     </select>
18     <select id="queryUser" parameterType="map" resultType="int">
19         select count(1) from tbUser where userName=#{userName} and password=#{password}
20     </select>
21 </mapper>
UserMapper.xml
 1 package com.wzz.model;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * @ClassName InfoMsg
 7  * @Description TODO   错误信息消息体
 8  * @Author AZhen
 9  * Version 1.0
10  **/
11 public class InfoMsg implements Serializable {
12     //自定义错误码    默认0表示正常执行
13     private String code="0";
14     //错误信息
15     private String message="操作成功";
16 
17     public String getCode() {
18         return code;
19     }
20 
21     public void setCode(String code) {
22         this.code = code;
23     }
24 
25     public String getMessage() {
26         return message;
27     }
28 
29     public void setMessage(String message) {
30         this.message = message;
31     }
32 }
InfoMsg.java
 1 package com.wzz.model;
 2 
 3 import com.wzz.common.DateUtil;
 4 
 5 import java.io.Serializable;
 6 
 7 /**
 8  * @ClassName ResponseBody
 9  * @Description TODO  封装响应的数据结构
10  * @Author AZhen
11  * Version 1.0
12  **/
13 public class ResponseBody<T> implements Serializable {
14     //时间
15     private String date= DateUtil.getCurrentDateStr("yyyy-MM-dd HH:mm:ss");
16     //状态码 默认200响应成功
17     private int status=200;
18     //接口返回的数据
19     private T data;
20 
21     public String getDate() {
22         return date;
23     }
24 
25     public void setDate(String date) {
26         this.date = date;
27     }
28 
29     public int getStatus() {
30         return status;
31     }
32 
33     public void setStatus(int status) {
34         this.status = status;
35     }
36 
37     public T getData() {
38         return data;
39     }
40 
41     public void setData(T data) {
42         this.data = data;
43     }
44 
45     public InfoMsg getInfo() {
46         return info;
47     }
48 
49     public void setInfo(InfoMsg info) {
50         this.info = info;
51     }
52 
53     //消息内容
54     private InfoMsg info;
55 
56 }
ResponseBody.java
 1 package com.wzz.model;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * @ClassName User
 7  * @Description TODO  用户类
 8  * @Author AZhen
 9  * Version 1.0
10  **/
11 public class User implements Serializable {
12     private String uid;    //uid
13     private String userName;   //用户名
14     private String password;    //密码
15     private String uName;      //姓名
16     private Integer age;    //年龄
17     private Integer sex;    //性别
18 
19     public String getUid() {
20         return uid;
21     }
22 
23     public void setUid(String uid) {
24         this.uid = uid;
25     }
26 
27     public String getUserName() {
28         return userName;
29     }
30 
31     public void setUserName(String userName) {
32         this.userName = userName;
33     }
34 
35     public String getPassword() {
36         return password;
37     }
38 
39     public void setPassword(String password) {
40         this.password = password;
41     }
42 
43     public String getuName() {
44         return uName;
45     }
46 
47     public void setuName(String uName) {
48         this.uName = uName;
49     }
50 
51     public Integer getAge() {
52         return age;
53     }
54 
55     public void setAge(Integer age) {
56         this.age = age;
57     }
58 
59     public Integer getSex() {
60         return sex;
61     }
62 
63     public void setSex(Integer sex) {
64         this.sex = sex;
65     }
66 
67     @Override
68     public String toString() {
69         return "User{" +
70                 "uid='" + uid + '\'' +
71                 ", userName='" + userName + '\'' +
72                 ", password='" + password + '\'' +
73                 ", uName='" + uName + '\'' +
74                 ", age=" + age +
75                 ", sex=" + sex +
76                 '}';
77     }
78 }
User.java
 1 package com.wzz.service.impl;
 2 
 3 import com.github.pagehelper.PageHelper;
 4 import com.github.pagehelper.PageInfo;
 5 import com.wzz.mapper.SysAccessLogMapper;
 6 import com.wzz.service.ISysAccessLogService;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 
10 import java.util.HashMap;
11 import java.util.List;
12 import java.util.Map;
13 
14 /**
15  * 系统访问日志实现类
16  * @ClassName SysAccessLogServiceImpl
17  * @Description TODO
18  * @Author AZhen
19  * Version 1.0
20  **/
21 @Service
22 public class SysAccessLogServiceImpl implements ISysAccessLogService {
23     @Autowired
24     private SysAccessLogMapper sysAccessLogMapper;
25     @Override
26     public Map<String, Object> querySysLogList(Map<String, Object> map) {
27         int pageNum=Integer.parseInt(map.get("pageNum").toString()); //当前页
28         int pageSize=Integer.parseInt(map.get("pageSize").toString());  //每页几条
29         PageHelper.startPage(pageNum,pageSize);
30         List<Map<String, Object>> resultList = sysAccessLogMapper.querySysLogList(map);
31         PageInfo pageInfo=new PageInfo(resultList);
32         long total = pageInfo.getTotal();  //总条数
33         Map<String,Object> resultMap=new HashMap<>();
34         resultMap.put("total",total);
35         resultMap.put("rows",resultList);
36         return resultMap;
37     }
38 
39     @Override
40     public int saveSysLog(Map<String, Object> map) {
41         return sysAccessLogMapper.saveSysLog(map);
42     }
43 }
SysAccessLogServiceImpl.java
 1 package com.wzz.service.impl;
 2 
 3 import com.github.pagehelper.PageHelper;
 4 import com.github.pagehelper.PageInfo;
 5 import com.wzz.mapper.UserMapper;
 6 import com.wzz.model.User;
 7 import com.wzz.service.IUserService;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Service;
10 
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 
15 /**
16  * @ClassName UserServiceImpl
17  * @Description TODO  用户业务层实现类
18  * @Author AZhen
19  * Version 1.0
20  **/
21 @Service
22 public class UserServiceImpl implements IUserService {
23     @Autowired
24     private UserMapper userMapper;
25     @Override
26     public Map<String,Object> queryUserList(Map<String, Object> map) {
27         int pageNum=Integer.parseInt(map.get("pageNum").toString()); //当前页
28         int pageSize=Integer.parseInt(map.get("pageSize").toString());  //每页几条
29         PageHelper.startPage(pageNum,pageSize);
30         List<User> userList = userMapper.queryUserList(map);
31         PageInfo pageInfo=new PageInfo(userList);
32         long total = pageInfo.getTotal();
33         Map<String,Object> resultMap=new HashMap<>();
34         resultMap.put("total",total);
35         resultMap.put("rows",userList);
36         return resultMap;
37     }
38 
39     @Override
40     public int queryUser(Map<String, Object> map) {
41         return userMapper.queryUser(map);
42     }
43 }
UserServiceImpl.java
 1 package com.wzz.service;
 2 
 3 import java.util.Map;
 4 
 5 /**
 6  * 系统访问日志接口
 7  * @ClassName ISysAccessLogService
 8  * @Description TODO
 9  * @Author AZhen
10  * Version 1.0
11  **/
12 public interface ISysAccessLogService {
13 
14     /**
15      * 查询系统日志列表
16      * @Author AZhen
17      * @Param [map]
18      * @return java.util.Map<java.lang.String,java.lang.Object>
19      **/
20     public Map<String,Object> querySysLogList(Map<String, Object> map);
21 
22     /**
23      * 保存日志
24      * @Author AZhen
25      * @Param [map]
26      * @return int
27      **/
28     public int saveSysLog(Map<String, Object> map);
29 }
ISysAccessLogService.java
 1 package com.wzz.service;
 2 
 3 import java.util.Map;
 4 
 5 /**
 6  * @ClassName IUserService
 7  * @Description TODO 用户业务层接口
 8  * @Author AZhen
 9  * Version 1.0
10  **/
11 public interface IUserService {
12     Map<String,Object> queryUserList(Map<String, Object> map);
13 
14     int queryUser(Map<String, Object> map);
15 }
IUserService.java

 三、功能小演示

  至此,小功能实现结束,有不足之处,请网友指正。谢谢<-_->

 

 posted on 2019-08-05 16:51  開開心欣  阅读(4357)  评论(3编辑  收藏  举报