Commit 0fd305e0 by xiaolang850403

初始版本

parents
# Editor directories and files
.mvn
.idea
target
logs
HELP.md
mvnw
mvnw.cmd
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.asset</groupId>
<artifactId>expert</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>expert</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
<exclusions>
<exclusion>
<artifactId>HikariCP</artifactId>
<groupId>com.zaxxer</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14-beta1</version>
</dependency>
<!-- 二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro和spring整合-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
# 资产管理系统
## 说明:
使用springboot + mybatis + Shiro组件组合的系统
## 环境:
java 1.8以上,mysql5.7以上
### 开发工具:
intellij idea
## 模块说明
main
-java
-com
-asset
-common //公共函数
-config //Druid的监控
-controller //控制器api方法入口
-domain //实体类
-filter //跨域过滤器
-mapper //操作数据库层
-service //接口的实现业务层
-shiro //认证授权中心
resources
-mybatis
-mapper //sql对应的xml文件
-application //系统的配置
-application-dev.yml //测试环境系统的服务及数据库配置
-application-prod.yml //正式环境系统的服务及数据库配置
-logback-spring.xml //系统日志配置
-shiro.ini //shiro认证配置
ValidationMessages.properties //api参数校验提示信息配置
pom.xml //系统项目的jar配置文件
### 请求字段
字段名 | 说明
---|---
keywords | 关键词
per | 每页数量
page | 页码
### 响应字段
字段名 | 说明
---|---
total | 总条目数
per_page | 每页显示条目个数
current_page | 当前页数
total_page | 总页数
### 数据库
字段名 | 说明
---|---
id | 主键
remark | 备注
created_at | 创建时间
updated_at | 修改时间
deleted_at | 删除时间
operated_at | 操作时间
package com.asset;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;
@MapperScan(value = "com.asset.mapper")
@SpringBootApplication
public class AssetsmanagementApplication {
public static void main(String[] args) {
SpringApplication.run(AssetsmanagementApplication.class, args);
}
}
package com.asset.common;
public enum CodeEnum {
SUCCESS(0,"操作成功!"),
//---系统错误返回码-----
SERVER_ERROR(10001,"服务器错误"),
URL_ERROR(10002,"接口不存在"),
PARAMETER_ERROR(10003,"参数不正确,校验失败"),
ERROR(10004,"操作失败"),
AUTH_ERROR(10005,"未授权"),
UN_LOGIN(10006,"未登录"),
//---用户操作返回码 2xxxx----
LOGIN_SUCCESS(20001,"登录成功!"),
LOGIN_ERROR(20002,"用户名或密码错误!"),
ISEXITE_ERROR(20003,"账号已经存在!"),
LOGINOUT_SUCCESS(20004,"成功!");
//---资产管理操作返回码 3xxxx----
//---资产盘点操作返回码 4xxxx----
//---资产报表操作返回码 5xxxx----
private int key;
private String value;
private CodeEnum(int key, String value) {
this.key = key;
this.value = value;
}
//根据ID值获取对应的描述
public static String getById(Integer id) {
for (CodeEnum typeEnum : values()) {
if (typeEnum.getKey() == id) {
return typeEnum.value;
}
}
return null;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package com.asset.common;
import org.apache.shiro.crypto.hash.SimpleHash;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* @author xiaol
* @date 2019/11/21
*/
public class Common {
//获取项目地址
public static String getUrl(HttpServletRequest request){
StringBuffer url = request.getRequestURL();
String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
return tempContextUrl;
}
//获取当前时间(日期格式)
public static String getDate(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
return df.format(new Date());
}
//获取当前时间(时间戳格式)
public static long getTime(){
return new Date().getTime();
}
//时间戳转换成字符串
public static String getDateToString(long time) {
Date d = new Date(time);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sf.format(d);
}
//字符串转换成时间戳
public static long getStringToDate(String time) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try{
date = sf.parse(time);
} catch(ParseException e) {
e.printStackTrace();
}
return date.getTime();
}
//字符串转换数组
public static String getStringToArray(String str) {
String[] arr = str.split(",");
return Arrays.toString(arr);
}
/**
*密码加密函数
*/
public static String passwordHash(Object credentials,Object salt) {
String hashAlgorithmName = "MD5";
int hashIterations = 3;
SimpleHash result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
return result.toString();
}
}
package com.asset.common;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/*
* @author xiaol
* @date 2019/12/30
*/
public class Excel {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
public Excel() {
}
/*
*导入相关函数
*/
public List<List<List<String>>> fileType(MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
String fileName = file.getOriginalFilename();
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
try {
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(in); //2003-
} else if (excel2007U.equals(fileType)){
wb = new XSSFWorkbook(in); //2007+
}
} catch (IOException e) {
e.printStackTrace();
}
List<List<List<String>>> listData = new ArrayList<>();
Sheet sheet = null;
for (int i=0;i<wb.getNumberOfSheets();i++){ //获取每个Sheet表
sheet=wb.getSheetAt(i);
//去掉空的Sheet
if(sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 0){
continue;
}
List<List<String>> sheetList = new ArrayList<>();
for (int j=0;j<sheet.getPhysicalNumberOfRows();j++){ //获取每行
XSSFRow row = (XSSFRow) sheet.getRow(j);
//去掉空行和表头
if (row == null || row.getFirstCellNum() == j) {
continue;
}
List<String> rowList = new ArrayList<String>();
for (int k=0;k<row.getPhysicalNumberOfCells();k++){ //获取每个单元格
if(row.getCell(k)!=null){
Cell cell = row.getCell(k);
rowList.add(getValue(cell));
}
}
sheetList.add(rowList);
}
listData.add(sheetList);
}
wb.close();
return listData;
}
/**
* 判断每个单元格的数据类型
*/
public static String getValue(Cell cell){
if(cell.getCellType() == Cell.CELL_TYPE_STRING){
return cell.getRichStringCellValue().getString();
}else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
if (DateUtil.isCellDateFormatted(cell)) {
return String.valueOf(cell.getDateCellValue());
/*Date d = cell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.format(d);*/
} else {
return String.valueOf(cell.getNumericCellValue());
}
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
return String.valueOf(cell.getBooleanCellValue());
}else{
return String.valueOf(cell.getStringCellValue());
}
}
/*
*导出相关函数
*/
/**
* 创建每个 sheet 页的数据
*/
public void createSheetData(XSSFWorkbook aWorkbook, String[] aTitles, String aSheetName,
List<String[]> aRowData) {
XSSFSheet tmpSheet = aWorkbook.createSheet(aSheetName);
// 设置sheet的标题
XSSFRow tmpTitileRow = tmpSheet.createRow(0);
for (int i = 0; i < aTitles.length; i++) {
tmpTitileRow.createCell(i).setCellValue(aTitles[i]);
}
// 遍历填充每行的数据
XSSFRow tmpRow = null;
int tmpRowNumber = 1;
for (String[] rowData : aRowData) {
tmpRow = tmpSheet.createRow(tmpRowNumber);
for (int i = 0; i < rowData.length; i++) {
tmpRow.createCell(i).setCellValue(rowData[i]);
}
tmpRowNumber++;
}
}
/**
* 设置响应头
*/
public void setResponseHeader(HttpServletResponse aResponse, String aFileName){
try {
try {
aFileName = new String(aFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
aResponse.setContentType("application/octet-stream;charset=ISO8859-1");
aResponse.setHeader("Content-Disposition", "attachment;filename=" + aFileName);
aResponse.addHeader("Pargam", "no-cache");
aResponse.addHeader("Cache-Control", "no-cache");
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package com.asset.common;
public interface Insert {
}
package com.asset.common;
public interface Login {
}
package com.asset.common;
import com.github.pagehelper.PageInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @author xiaol
* @date 2019/12/28
*/
public class Pagination {
public static Map Pagination(List list) {
//分页查询,包括分页和总数查询,第三个参数是控制是否计算总数,默认是true,true为查询总数,分页效果只对其后的第一个查询有效。
PageInfo pageOb = new PageInfo(list);
//组合数组
Map<String, Object> map=new HashMap<String, Object>();
map.put("total_page", pageOb.getPages());
map.put("total", pageOb.getTotal());
map.put("per_page", pageOb.getPageSize());
map.put("current_page", pageOb.getPageNum());
map.put("list", list);
return map;
}
}
package com.asset.common;
import com.google.zxing.*;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
/*
* @author xiaol
* @date 2020/01/02
*/
public class QRCode {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCode.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
BufferedImage src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = (BufferedImage) image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,
boolean needCompress) throws Exception {
BufferedImage image = QRCode.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
return file;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* @author lanyuan
* Email: mmm333zzz520@163.com
* @date 2013-12-11 上午10:16:36
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath)
throws Exception {
QRCode.encode(content, imgPath, destPath, false);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress) throws Exception {
QRCode.encode(content, null, destPath, needCompress);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath) throws Exception {
QRCode.encode(content, null, destPath, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCode.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param output
* 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCode.encode(content, null, output, false);
}
/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
*
* @param path
* 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCode.decode(new File(path));
}
}
package com.asset.common;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/*
* @author xiaol
* @date 2020/01/02
*/
public class QRCodeUtil {
public static BitMatrix generateQRCodeStream(String content, HttpServletResponse response,int width,int height) {
//给相应添加头部信息,主要告诉浏览器返回的是图片流
response.setHeader("Cache-Control", "no-store");
// 不设置缓存
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/png");
//设置图片的文字编码以及内边框
Map<EncodeHintType, Object> hints = new HashMap<>();
//编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//边框距
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix;
try {
//参数分别为:编码内容、编码类型、图片宽度、图片高度,设置参数
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
}catch(WriterException e) {
e.printStackTrace();
return null;
}
return bitMatrix;
}
public static BitMatrix generateQRCodeStream(String content, int width,int height) {
//设置图片的文字编码以及内边框
Map<EncodeHintType, Object> hints = new HashMap<>();
//编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//边框距
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix;
try {
//参数分别为:编码内容、编码类型、图片宽度、图片高度,设置参数
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
}catch(WriterException e) {
e.printStackTrace();
return null;
}
return bitMatrix;
}
}
package com.asset.common;
/*
* @author xiaol
* @date 2019/12/25
*/
/**
* 公共的返回码
* 返回码code:
* 成功:0
* 失败:10001
*/
public class Result<T> {
/** 错误码. */
private Integer code;
/** 提示信息. */
private String msg;
/** 具体的内容. */
private T data;
public Result() {
super();
}
public Result(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
package com.asset.common;
/*
* @author xiaol
* @date 2019/12/25
*/
/**
* 公共的返回码
* 返回码code:
* 成功:0
* 失败:10001
*/
public enum ResultCode {
SUCCESS(0,"操作成功!"),
//---系统错误返回码-----
SERVER_ERROR(10001,"服务器错误"),
URL_ERROR(10002,"接口不存在"),
PARAMETER_ERROR(10003,"参数不正确");
//---用户操作返回码 2xxxx----
//---企业操作返回码 3xxxx----
//---权限操作返回码----
//---其他操作返回码----
//操作代码
int code;
//提示信息
String message;
ResultCode(int code, String message){
this.code = code;
this.message = message;
}
public int code() {
return code;
}
public String message() {
return message;
}
}
package com.asset.common;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
/*
* @author xiaol
* @date 2019/12/25
*/
public class ResultUtil {
public static Result success(CodeEnum CodeEnum, Object object) {
Result result = new Result();
result.setCode(CodeEnum.getKey());
result.setMsg(CodeEnum.getValue());
result.setData(object);
return result;
}
public static Result success() {
return success(null);
}
public static Result success(CodeEnum CodeEnum) {
Result result = new Result();
result.setCode(CodeEnum.getKey());
result.setMsg(CodeEnum.getValue());
return result;
}
public static Result error(CodeEnum CodeEnum) {
Result result = new Result();
result.setCode(CodeEnum.getKey());
result.setMsg(CodeEnum.getValue());
return result;
}
public static Result error(CodeEnum CodeEnum, Object object) {
Result result = new Result();
result.setCode(CodeEnum.getKey());
result.setMsg(CodeEnum.getValue());
result.setData(object);
return result;
}
public static Result Validated(BindingResult result) {
String errorMesssage = CodeEnum.PARAMETER_ERROR.getValue();
for (FieldError fieldError : result.getFieldErrors()) {
errorMesssage += fieldError.getDefaultMessage() + ", ";
}
CodeEnum.PARAMETER_ERROR.setValue(errorMesssage);
return error(CodeEnum.PARAMETER_ERROR);
}
}
package com.asset.common;
public interface Special {
}
package com.asset.common;
public enum StatusEnum {
ON(0,"正常"),
NO(1,"锁定");
private int key;
private String value;
private StatusEnum(int key, String value) {
this.key = key;
this.value = value;
}
//根据ID值获取对应的描述
public static String getById(Integer id) {
for (StatusEnum statusEnum : values()) {
if (statusEnum.getKey() == id) {
return statusEnum.value;
}
}
return null;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package com.asset.common;
public interface Update {
}
package com.asset.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/*
* @author xiaol
* @date 2019/12/28
*/
public class Upload {
//函数重载,使用新名字还是保持原文件名不变
public Map Upload(MultipartFile file,String filePath,String tempContextUrl) throws IOException {
//上传文件原始名称
String originalFilename = file.getOriginalFilename();
//新的图片名称
String newFileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
//新文件
File file1 = new File(filePath+newFileName);
//将内存中的文件写入磁盘
file.transferTo(file1);
String Path = tempContextUrl + newFileName;
String url = filePath + newFileName;
//Runtime.getRuntime().exec("chmod 777 -R " + url);
Map<String, Object> map = new HashMap<>();
map.put("filename", newFileName);
map.put("filepath", Path);
return map;
}
public Map Upload(MultipartFile file,String filePath,String tempContextUrl,boolean isName) throws IOException {
String newFileName = null;
//上传文件原始名称
String originalFilename = file.getOriginalFilename();
if(isName == true){
//新的图片名称
newFileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
}else{
newFileName = originalFilename;
}
File file1 = new File(filePath+newFileName);
//将内存中的文件写入磁盘
file.transferTo(file1);
String Path = tempContextUrl + newFileName;
String url = filePath + newFileName;
//Runtime.getRuntime().exec("chmod 777 -R " + url);
Map<String, Object> map = new HashMap<>();
map.put("filename", newFileName);
map.put("filepath", Path);
return map;
}
}
package com.asset.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/*
* @author xiaol
* @date 2019/12/26
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//配置一个管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,Object> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");
initParams.put("deny","192.168.0.51");
bean.setInitParameters(initParams);
return bean;
}
//配置一份web监控
public FilterRegistrationBean WebStatFilter(){
//通过FilterRegistrationBean实例设置优先级可以生效
//通过@WebFilter无效
FilterRegistrationBean bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());//注册自定义过滤器
Map<String,Object> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
package com.asset.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true); //驼峰配置写法
}
};
}
}
package com.asset.controller;
import com.asset.common.*;
import com.asset.domain.User;
import com.asset.mapper.UserMapper;
import com.asset.service.UserService;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @author xiaol
* @date 2020/1/3
*/
@RestController
public class UserController {
@Autowired
UserService userService;
@Autowired
UserMapper userMapper;
@RequestMapping("/login")
public Result login(@Validated(value={Login.class}) @RequestBody User user, BindingResult result){
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
try {
String name = user.getUsername();
String password = user.getPassword();
password = new Md5Hash(password,name,3).toString();
UsernamePasswordToken upToken = new UsernamePasswordToken(name,password);
//1.获取subject
Subject subject = SecurityUtils.getSubject();
//获取session
String sid = (String) subject.getSession().getId();
//2.调用subject进行登录
subject.login(upToken);
return ResultUtil.success(CodeEnum.LOGIN_SUCCESS);
}catch (Exception e) {
return ResultUtil.error(CodeEnum.LOGIN_ERROR);
}
}
@RequestMapping("/loginOut")
public Result loginOut(){
try {
//1.获取subject
Subject subject = SecurityUtils.getSubject();
//2.调用subject进行登出
subject.logout();
return ResultUtil.success(CodeEnum.LOGINOUT_SUCCESS);
}catch (Exception e) {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping(value = "/user/getUserInfo")
public Result getUserInfo() {
User user = (User) SecurityUtils.getSubject().getPrincipal();
return ResultUtil.success(CodeEnum.SUCCESS,user);
}
@RequestMapping(value = "/user/getUserById")
public Result getUserById(int id) {
Map<String,Object> user = userService.getUserByIdInfo(id);
/*String hashAlgorithmName = "MD5";
Object credentials = "123456";
Object salt = "xiaol";
int hashIterations = 3;
Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);*/
System.out.println(user);
return ResultUtil.success(CodeEnum.SUCCESS,user);
}
@RequestMapping(value = "/user/getUserList")
public Result getUserList(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int per,@RequestParam(value="username",required=false)String username) {
PageHelper.startPage(page, per);
Map param = new HashMap();
param.put("username",username);
List<User> lists = userService.getUserList(param);
Map map = Pagination.Pagination(lists);
return ResultUtil.success(CodeEnum.SUCCESS,map);
}
@RequestMapping(value = "/user/addUser")
public Result addUser(@Validated(value={Insert.class}) @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
if(userService.getUserByName(user.getUsername()) != null){
return ResultUtil.error(CodeEnum.ISEXITE_ERROR);
}
System.out.println(user.getPassword());
user.setCreate_time(Common.getTime());
String password = Common.passwordHash(user.getPassword(),user.getUsername());
user.setPassword(password);
if (userService.insertUser(user)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping(value = "/user/updateUser")
public Result updateUser(@Validated(value={Update.class}) @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
System.out.println(user);
if (userService.updateUser(user)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping(value = "/user/updatePassword")
public Result updatePassword(@Validated(value={Special.class}) @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
System.out.println(user);
if (userService.updatePassword(user)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping(value = "/user/deleteUser")
public Result deleteUserById(Integer id) {
if (userService.deleteUserById(id)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping(value = "/autherror")
public Result autherror(int code){
return code == 0 ? ResultUtil.error(CodeEnum.UN_LOGIN) : ResultUtil.error(CodeEnum.AUTH_ERROR);
}
@RequestMapping(value = "/errorPage")
public Result errorPage(int code,HttpServletRequest request){
return code == 0 ? ResultUtil.success(CodeEnum.SUCCESS) : ResultUtil.error(CodeEnum.ERROR,getStatus(request));
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
try {
return HttpStatus.valueOf(statusCode);
}
catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}
package com.asset.controller.system;
import com.asset.common.*;
import com.asset.domain.system.Company;
import com.asset.service.UserService;
import com.asset.service.system.CompanyService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @author xiaol
* @date 2019/12/26
*/
@RestController
public class CompanyController {
@Autowired
CompanyService companyService;
@Autowired
UserService userService;
//图片访问域名
@Value("${tempContextUrl}")
private String tempContextUrl;
//图片存储目录
@Value("${filePath}")
private String filePath;
@GetMapping("/getCompanyById")
public Result getCompany(Integer id){
Company company = companyService.getCompanyById(id);
return ResultUtil.success(CodeEnum.SUCCESS,company);
}
@GetMapping(value = "listCompany")
public Result companyList(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int per,String name) {
PageHelper.startPage(page, per);
Map param = new HashMap();
param.put("name",name);
Page<Company> list = companyService.companyList(param);
Map map = Pagination.Pagination(list);
return ResultUtil.success(CodeEnum.SUCCESS,map);
}
@PostMapping("/insertCompany")
public Result insertCompany(@Validated(value={Insert.class}) @RequestBody Company company, BindingResult result){
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
System.out.println(Common.getTime());
company.setCreateTime((int) Common.getTime());
long ss = Common.getTime();
System.out.println(Common.getDateToString(ss));
companyService.insertCompany(company);
return ResultUtil.success(CodeEnum.SUCCESS);
}
@PostMapping("/updateCompany")
public Result updateCompany(@Validated(value={Update.class}) @RequestBody Company company, BindingResult result){
if (result.hasErrors()) {
return ResultUtil.Validated(result);
}
companyService.updateCompany(company);
return ResultUtil.success(CodeEnum.SUCCESS);
}
@GetMapping("/deleteCompanyById")
public Result deleteCompanyById(Integer id){
if (companyService.deleteCompanyById(id)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
@RequestMapping("/deleteCompanyByIds")
public Result deleteCompanyByIds(String ids,String name){
String[] arr = ids.split(",");
List list = new ArrayList();
for (int i=0;i<arr.length;i++){
list.add(arr[i]);
}
System.out.println(list);
if (companyService.deleteCompanyByIds(list,name)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
/*
* 上传文件
*/
@RequestMapping("/upload")
public Result upload(MultipartFile file) throws IOException {
if(file!=null && file.getOriginalFilename()!=null && file.getOriginalFilename().length()>0){
Upload upload = new Upload();
Map map = upload.Upload(file, filePath, tempContextUrl,true);
return ResultUtil.success(CodeEnum.SUCCESS,map);
}
return ResultUtil.error(CodeEnum.ERROR);
}
/*
* 导入Excel
*/
@RequestMapping("/importDo")
public Result importDo(MultipartFile file) throws IOException {
Excel excel = new Excel();
List<List<List<String>>> listData = excel.fileType(file);
List<Company> list = new ArrayList<Company>();
for (int i = 0; i < listData.size(); i++) {
for (int j =0; j < listData.get(i).size(); j++){
Company company = new Company();
company.setName(listData.get(i).get(j).get(0));
company.setAddress(listData.get(i).get(j).get(1));
company.setPhone(listData.get(i).get(j).get(2));
company.setState(listData.get(i).get(j).get(3));
company.setCreateTime((int) Common.getTime());
list.add(company);
}
}
if (companyService.insertAllCompany(list)) {
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}
}
/*
*导出
*/
@RequestMapping("/downloadDo")
public void downloadDo(HttpServletResponse response, String name) throws Exception {
XSSFWorkbook tmpWorkbook = new XSSFWorkbook();
String[] tmpUserTitles = {"序号", "公司名称", "地址", "电话", "状态", "创建时间"};
List<Company> companyLists = (List<Company>) companyService.getCompanyByName(name);
List<String[]> companys = new ArrayList<>();
for (Company companyList : companyLists) {
String[] company = new String[5];
company[0] = String.valueOf(companyList.getId());
company[1] = companyList.getName();
company[2] = companyList.getAddress();
company[3] = companyList.getPhone();
company[4] = companyList.getState();
company[5] = String.valueOf(companyList.getCreateTime());
companys.add(company);
}
Excel excel = new Excel();
excel.createSheetData(tmpWorkbook, tmpUserTitles, "列表", companys);
String filename = "列表" + Common.getDate() + ".xlsx";
excel.setResponseHeader(response, filename);
OutputStream tmpOutputStream = response.getOutputStream();
tmpWorkbook.write(tmpOutputStream);
tmpOutputStream.flush();
tmpOutputStream.close();
}
/*
*生成二维码(直接显示页面上)
*/
@RequestMapping("/generateQRCode")
public void generateQRCode(HttpServletResponse response,String name) {
String longUrl;
try {
longUrl = "http://www.ecrrc.com" + name;
// 生成二维码
BitMatrix qRcodeImg = QRCodeUtil.generateQRCodeStream(longUrl, response,300,300);
// 将二维码输出到页面中
MatrixToImageWriter.writeToStream(qRcodeImg, "png", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
*生成二维码(指定路径生成图片)
*/
@RequestMapping("/createQRCode")
public Result createQRCode(String name) throws Exception {
String text = "http://www.baidu.com";
String destPath = "D:\\phpStudy\\WWW\\images\\";
QRCode.encode(text, null, destPath, true);
return ResultUtil.success(CodeEnum.SUCCESS);
}
}
package com.asset.domain;
import com.asset.common.Insert;
import com.asset.common.Login;
import com.asset.common.Special;
import com.asset.common.Update;
import lombok.Data;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.List;
/*
* @author xiaol
* @date 2020/1/3
*/
@Data
public class User {
@Id
private Integer id;
/**
* 账号
*/
@NotEmpty(message = "{username.NotEmpty}", groups = {Insert.class,Login.class})
private String username;
/**
* 密码
*/
@NotEmpty(message = "{password.NotEmpty}", groups = {Insert.class,Special.class,Login.class})
@Pattern(regexp="^[a-zA-Z0-9]+$",message="{password.Pattern}",groups = {Insert.class,Special.class,Login.class})
@Size(min=6,max=20,message="{password.size}",groups = {Insert.class,Special.class,Login.class})
private String password;
private String name;
private String depid;
private Long phone;
private String email;
private Integer status;
private Integer sex;
private Long create_time;
/**
* 映射的角色
*/
private List<String> role;
/**
* 映射的权限
*/
private List<String> permission;
@NotEmpty(message = "{password.NotEmpty}", groups = {Insert.class,Update.class})
private String role_id;
}
package com.asset.domain.system;
import com.asset.common.Insert;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class Company {
//ID
private Integer id;
/**
* 公司名称
*/
@NotEmpty(message = "名称不能为空!", groups = {Insert.class})
private String name;
/**
* 公司地址
*/
private String address;
/**
* 公司电话
*/
private String phone;
/**
* 状态
*/
private String state;
/**
* 创建时间
*/
private Integer createTime;
}
package com.asset.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* @author xiaol
* @date 2020/1/7
*/
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
package com.asset.mapper;
import com.asset.domain.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public interface UserMapper {
public User getUserById(Integer id);
public User getUserByName(String name);
List<User> getUserList(Map param);
public boolean insertUser(User user);
public boolean deleteUserById(Integer id);
public boolean updateUser(User user);
public boolean updatePassword(User user);
}
package com.asset.mapper.system;
import com.asset.domain.system.Company;
import com.github.pagehelper.Page;
import java.util.List;
import java.util.Map;
public interface CompanyMapper {
//@Select("select * from company where id=#{id}")
public Company getCompanyById(Integer id);
public Company getCompanyByName(String name);
Page<Company> companyList(Map param);
public void insertCompany(Company company);
public boolean insertAllCompany(List<Company> company);
public void updateCompany(Company company);
public boolean deleteCompanyById(Integer id);
/* @Delete("<script>" +
"delete from company where id in " +
"<foreach collection='list' item='team' open='(' separator=',' close=')'>"
+"#{team}"
+"</foreach>"
+"</script>")*/
public boolean deleteCompanyByIds(List<Integer> list, String name);
}
package com.asset.service;
import com.asset.common.Common;
import com.asset.domain.*;
import com.asset.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* @author xiaol
* @date 2019/12/28
*/
@Service("UserService")
public class UserService implements UserMapper {
@Autowired
UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
public Map<String,Object> getUserByIdInfo(Integer id) {
User user = getUserById(id);
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("username", user.getUsername());
map.put("name", user.getName());
map.put("depid", user.getDepid());
map.put("sex", user.getSex());
map.put("phone", user.getPhone());
map.put("email", user.getEmail());
return map;
}
@Override
public User getUserByName(String name) {
return userMapper.getUserByName(name);
}
@Override
public List<User> getUserList(Map param) {
List<User> lists = userMapper.getUserList(param);
return lists;
}
@Override
public boolean insertUser(User user) {
//需要同步写入账号对应的角色到账号角色表(需要获取insert的账号id)
return userMapper.insertUser(user);
}
@Override
public boolean deleteUserById(Integer id) {
return userMapper.deleteUserById(id);
}
@Override
public boolean updateUser(User user) {
if(userMapper.updateUser(user)){
return true;
}else{
return false;
}
}
@Override
public boolean updatePassword(User user) {
User user1 = userMapper.getUserById(user.getId());
String password = Common.passwordHash(user.getPassword(),user1.getUsername());
user.setPassword(password);
return userMapper.updatePassword(user);
}
}
package com.asset.service.system;
import com.asset.domain.system.Company;
import com.asset.mapper.system.CompanyMapper;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/*
* @author xiaol
* @date 2019/12/28
*/
@Service("CompanyService")
public class CompanyService implements CompanyMapper {
@Autowired
CompanyMapper companyMapper;
@Override
public Company getCompanyById(Integer id) {
return companyMapper.getCompanyById(id);
}
@Override
public Company getCompanyByName(String name) {
return companyMapper.getCompanyByName(name);
}
@Override
public Page<Company> companyList(Map param) {
return companyMapper.companyList(param);
}
@Override
public void insertCompany(Company company) {
companyMapper.insertCompany(company);
}
@Override
public boolean insertAllCompany(List<Company> company) {
return companyMapper.insertAllCompany(company);
}
@Override
public void updateCompany(Company company) {
companyMapper.updateCompany(company);
}
@Override
public boolean deleteCompanyById(Integer id) {
return companyMapper.deleteCompanyById(id);
}
@Override
public boolean deleteCompanyByIds(List<Integer> list,String name) {
return companyMapper.deleteCompanyByIds(list,name);
}
}
package com.asset.utils;
import com.asset.common.CodeEnum;
import com.asset.common.Result;
import com.asset.common.ResultUtil;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlableExceptionHandle {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result myExceptionHandler(Exception ex){
return ResultUtil.error(CodeEnum.ERROR,ex.getMessage());
}
@Bean
public WebServerFactoryCustomizer webServerFactoryCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
@Override
public void customize(ConfigurableWebServerFactory factory) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPage?code=10004");
ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/errorPage?code=10004");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPage?code=10004");
factory.addErrorPages( error404Page,error400Page,errorPage500);
}
};
}
}
#账号相关
username.NotEmpty=账号不能为空
password.NotEmpty=密码不能为空
password.Pattern=密码必须是数字或字母
password.size=密码由6到20位数组或字母组成
#角色
role.NotEmpty=角色名不能为空
#菜单
menu.titleNotEmpty=菜单名不能为空
menu.urlNotEmpty=菜单链接不能为空
menu.peridNotEmpty=菜单对应的api不能为空
#权限
permission.nameNotEmpty=api权限名不能为空
permission.codeNotEmpty=权限规则名不能为空
permission.urlNotEmpty=权限链接不能为空
#服务配置
server:
port: 9003
servlet:
context-path: /api
#spring配置
spring:
#2.数据库连接池
datasource:
username: root
password: 123456
url: jdbc:mysql://152.136.188.17:3306/assets?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*Mapper.xml
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count==countSql
page-size-zero: true
#日志
logging:
file:
path: /Users/langxiao/Code/java/assets/logs
name: my.log.%d{yyyy-MM-dd}.log
max-history: 30
max-size: 10MB
level:
root: info
\ No newline at end of file
#服务配置
server:
port: 9002
servlet:
context-path: /api
#spring配置
spring:
#2.数据库连接池
datasource:
username: root
password: root
url: jdbc:mysql://152.136.188.17:3306/assets?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*Mapper.xml
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count==countSql
page-size-zero: true
#日志
logging:
file:
path: logs
name: my.log.%d{yyyy-MM-dd}.log
max-history: 30
max-size: 10MB
level:
root: info
\ No newline at end of file
spring.profiles.active = dev
#图片存储目录
filePath=D:/phpStudy/WWW/images/
#图片访问域名
tempContextUrl=http://localhost:8002/
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
<springProperty scope="context" name="filePath" source="logging.file.path"/>
<springProperty scope="context" name="fileName" source="logging.file.name"/>
<springProperty scope="context" name="fileMaxHistory" source="logging.file.max-history"/>
<springProperty scope="context" name="fileMaxSize" source="logging.file.max-size"/>
<springProperty scope="context" name="levelRoot" source="logging.level.root"/>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${filePath}/${fileName}</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>${fileMaxHistory}</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>${fileMaxSize}</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 日志输出级别 -->
<root level="${levelRoot}">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.asset.mapper.system.CompanyMapper">
<resultMap id="BaseResultMap" type="com.asset.domain.system.Company">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="address" jdbcType="VARCHAR" property="address"/>
<result column="phone" jdbcType="VARCHAR" property="phone"/>
<result column="state" jdbcType="INTEGER" property="state"/>
<result column="createTime" jdbcType="BIGINT" property="createTime"/>
</resultMap>
<sql id="Base_Column_List">
id, name, address, phone, state, createTime
</sql>
<select id="getCompanyById" resultType="com.asset.domain.system.Company">
select * from company where id = #{id}
</select>
<select id="getCompanyByName" resultType="com.asset.domain.system.Company">
select * from company where name = #{name}
</select>
<insert id="insertCompany" parameterType="com.asset.domain.system.Company">
insert into company(name,address,phone,state,createTime) value (#{name},#{address},#{phone},#{state},#{createTime})
</insert>
<insert id="insertAllCompany" parameterType="com.asset.domain.system.Company">
insert into company(name,address,phone,state,createTime) value
<foreach collection='list' item='item' separator=','>
(#{item.name},#{item.address},#{item.phone},#{item.state},#{item.createTime})
</foreach>
</insert>
<update id="updateCompany" parameterType="com.asset.domain.system.Company">
update company set name=#{name},address=#{address},phone=#{phone},state=#{state} where id=#{id}
</update>
<select id="companyList" parameterType="Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from company
where 1=1
<if test="name != null">
and name = #{name}
</if>
</select>
<delete id="deleteCompanyById" >
delete from company where id=#{id}
</delete>
<delete id="deleteCompanyByIds">
delete from company where id in
<foreach collection='list' item='item' open='(' separator=',' close=')'>
#{item}
</foreach>
<if test="name != null">
and name = #{name}
</if>
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.asset.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.asset.domain.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="depid" jdbcType="VARCHAR" property="depid"/>
<result column="phone" jdbcType="VARCHAR" property="phone"/>
<result column="email" jdbcType="VARCHAR" property="email"/>
<result column="sex" jdbcType="INTEGER" property="sex"/>
<result column="create_time" jdbcType="VARCHAR" property="create_time"/>
</resultMap>
<sql id="Base_Column_List">
id, username, password,name,phone,email
</sql>
<select id="getUserById" resultMap="BaseResultMap">
select * from user where id=#{id}
</select>
<select id="getUserByName" resultMap="BaseResultMap">
select * from user where username = #{username}
</select>
<select id="getUserList" resultMap="BaseResultMap">
select * from user
</select>
<insert id="insertUser" parameterType="com.asset.domain.User">
insert into user(username,password,name,status,phone,email,depid,create_time) value (#{username},#{password},#{name},#{status},#{phone},#{email},#{depid},#{create_time})
</insert>
<delete id="deleteUserById" >
delete from user where id=#{id}
</delete>
<update id="updateUser" parameterType="com.asset.domain.User">
update user set name=#{name},sex=#{sex},phone=#{phone},email=#{email},depid=#{depid} where id=#{id}
</update>
<update id="updatePassword" parameterType="com.asset.domain.User">
update user set password=#{password} where id=#{id}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
\ No newline at end of file
package com.asset;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class AssetsmanagementApplicationTests {
@Autowired
DataSource dataSource;
private SecurityManager securityManager;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
/**
* 测试用户认证:
* 认证:用户登录
* 1.根据配置文件创建SecurityManagerFactory
* 2.通过工厂获取SecurityManager
* 3.将SecurityManager绑定到当前运行环境
* 4.从当前运行环境中构造subject
* 5.构造shiro登录的数据
* 6.主体登陆
*/
@Test
public void testLogin() {
//1.根据配置文件创建securityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
//2.获取SecurityManager
securityManager.setAuthenticator(authenticator);
ModularRealmAuthorizer realmAuthorizer = new ModularRealmAuthorizer();
realmAuthorizer.setPermissionResolver(new WildcardPermissionResolver());
securityManager.setAuthorizer(realmAuthorizer);
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
//3.将SecurityManager绑定到当前运行环境
SecurityUtils.setSecurityManager(securityManager);
//4.从当前运行环境中构造subject
Subject subject = SecurityUtils.getSubject();
//5.构造shiro登录的数据
String username = "lisi";
String password = "123456";
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//6.主体登陆
try{
// 4、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
// 5、身份验证失败
System.out.println("用户身份验证失败");
e.printStackTrace();
}
//7.验证用户是否登录成功
Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录
if (subject.isAuthenticated()) {
System.out.println("用户登录成功="+subject.isAuthenticated());
} else {
System.out.println("用户登录失败");
}
//8.获取登录成功的数据
System.out.println(subject.getPrincipal());
//登录成功之后,完成授权
//授权:检验当前登录用户是否具有操作权限,是否具有某个角色
System.out.println(subject.hasRole("role1"));
System.out.println(subject.isPermitted("user:save"));
}
@Test
public void testLogin2() {
/*//1.根据配置文件创建securityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
//2.获取SecurityManager
securityManager.setAuthenticator(authenticator);
ModularRealmAuthorizer realmAuthorizer = new ModularRealmAuthorizer();
realmAuthorizer.setPermissionResolver(new WildcardPermissionResolver());
securityManager.setAuthorizer(realmAuthorizer);
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
//3.将SecurityManager绑定到当前运行环境
SecurityUtils.setSecurityManager(securityManager);
//4.从当前运行环境中构造subject
Subject subject = SecurityUtils.getSubject();
//5.构造shiro登录的数据
String username = "zhangsan";
String password = "123456";
UsernamePasswordToken token = new UsernamePasswordToken(username,password);*/
//1.根据配置文件创建SecurityManagerFactory
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2.通过工厂获取SecurityManager
SecurityManager securityManager = factory.getInstance();
//3.将SecurityManager绑定到当前运行环境
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
String username = "zhangsan";
String password = "123456";
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//执行login-->realm域中的认证方法
//6.主体登陆
try{
// 4、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
// 5、身份验证失败
System.out.println("用户身份验证失败");
e.printStackTrace();
}
//7.验证用户是否登录成功
Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录
if (subject.isAuthenticated()) {
System.out.println("用户登录成功="+subject.isAuthenticated());
} else {
System.out.println("用户登录失败");
}
//授权:-->realm域中的授权方法
System.out.println(subject.hasRole("role1"));
System.out.println(subject.isPermitted("user:save"));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment