Commit 77aad3c2 by xiaolang850403

日常提交

parent 0fd305e0
......@@ -88,29 +88,7 @@
<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>
......
# 资产管理系统
# 评标专家系统
## 说明:
使用springboot + mybatis + Shiro组件组合的系统
使用springboot + mybatis 组件组合的系统
## 环境:
java 1.8以上,mysql5.7以上
......@@ -21,7 +21,6 @@ intellij idea
-filter //跨域过滤器
-mapper //操作数据库层
-service //接口的实现业务层
-shiro //认证授权中心
resources
-mybatis
-mapper //sql对应的xml文件
......@@ -29,7 +28,6 @@ intellij idea
-application-dev.yml //测试环境系统的服务及数据库配置
-application-prod.yml //正式环境系统的服务及数据库配置
-logback-spring.xml //系统日志配置
-shiro.ini //shiro认证配置
ValidationMessages.properties //api参数校验提示信息配置
pom.xml //系统项目的jar配置文件
......@@ -61,4 +59,3 @@ remark | 备注
created_at | 创建时间
updated_at | 修改时间
deleted_at | 删除时间
operated_at | 操作时间
......@@ -6,10 +6,10 @@ import org.mybatis.spring.annotation.MapperScan;
@MapperScan(value = "com.asset.mapper")
@SpringBootApplication
public class AssetsmanagementApplication {
public class ExpertApplication {
public static void main(String[] args) {
SpringApplication.run(AssetsmanagementApplication.class, args);
SpringApplication.run(ExpertApplication.class, args);
}
}
package com.asset.common;
import org.apache.shiro.crypto.hash.SimpleHash;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
......@@ -54,13 +53,4 @@ public class Common {
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 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;
}
}
......@@ -4,29 +4,17 @@ 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
* @date 2020/03/02
*/
@RestController
public class UserController {
......@@ -34,146 +22,19 @@ 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)) {
@RequestMapping("/register")
public Result register(@Validated(value={Insert.class}) @RequestBody User user, BindingResult result){
if(userService.insertUser(user)){
return ResultUtil.success(CodeEnum.SUCCESS);
} else {
return ResultUtil.error(CodeEnum.ERROR);
}else{
return ResultUtil.success(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;
}
@RequestMapping("/login")
public Result login(@Validated(value={Login.class}) @RequestBody User user, BindingResult result){
return ResultUtil.success(CodeEnum.SUCCESS);
}
}
package com.asset.controller.system;
public class AreaController {
}
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.controller.system;
import org.springframework.web.bind.annotation.RestController;
/*
* @author xiaol
* @date 2020/02/29
*/
@RestController
public class DisciplineController {
}
......@@ -13,7 +13,7 @@ import java.util.List;
/*
* @author xiaol
* @date 2020/1/3
* @date 2020/02/28
*/
@Data
public class User {
......@@ -22,8 +22,8 @@ public class User {
/**
* 账号
*/
@NotEmpty(message = "{username.NotEmpty}", groups = {Insert.class,Login.class})
private String username;
@NotEmpty(message = "{name.NotEmpty}", groups = {Insert.class,Login.class})
private String name;
/**
* 密码
*/
......@@ -32,29 +32,42 @@ public class User {
@Size(min=6,max=20,message="{password.size}",groups = {Insert.class,Special.class,Login.class})
private String password;
private String name;
private String title;
private String depid;
private String sex;
private Long phone;
private Long mobile;
private String email;
private Integer status;
private Integer state;
private Integer sex;
private String province;
private Long create_time;
/**
* 映射的角色
*/
private List<String> role;
/**
* 映射的权限
*/
private List<String> permission;
private Long create_at;
@NotEmpty(message = "{card_front.NotEmpty}", groups = {Insert.class,Update.class})
private String card_front;
private String card_obverse;
private String school_id;
private String discipline_id;
private String job_id;
private String employer;
private String city;
private String county;
private String address;
private String is_expert;
@NotEmpty(message = "{password.NotEmpty}", groups = {Insert.class,Update.class})
private String role_id;
private String expert_type;
private String expert_type_value;
}
package com.asset.domain.system;
import lombok.Data;
@Data
public class Area {
private Integer id;
private String name;
private Integer pid;
}
package com.asset.domain.system;
import lombok.Data;
@Data
public class Certificate {
private Integer id;
private String image;
private Integer user_id;
private Integer type;
private long create_at;
}
......@@ -6,29 +6,13 @@ import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class Company {
public class Discipline {
//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.domain.system;
import lombok.Data;
@Data
public class Job {
private Integer id;
private String name;
}
package com.asset.domain.system;
import lombok.Data;
@Data
public class School {
private Integer id;
private String name;
}
......@@ -19,5 +19,4 @@ public interface UserMapper {
public boolean updateUser(User user);
public boolean updatePassword(User user);
}
package com.asset.mapper.system;
import com.asset.domain.system.Certificate;
import com.asset.domain.system.Discipline;
import com.github.pagehelper.Page;
import java.util.Map;
public interface CertificateMapper {
public Certificate getCertificateById(Integer id);
public Certificate getCertificateByUserId(Integer user_id);
Page<Certificate> getCertificateList();
public boolean insertCertificate(Certificate certificate);
public boolean deleteCertificateById(Integer id);
public boolean updateCertificate(Certificate certificate);
}
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.mapper.system;
import com.asset.domain.system.Discipline;
import com.github.pagehelper.Page;
import java.util.Map;
public interface DisciplineMapper {
public Discipline getDisciplineById(Integer id);
Page<Discipline> disciplineList(Map param);
}
......@@ -23,19 +23,6 @@ public class UserService implements UserMapper {
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);
......@@ -49,9 +36,10 @@ public class UserService implements UserMapper {
@Override
public boolean insertUser(User user) {
//需要同步写入账号对应的角色到账号角色表(需要获取insert的账号id)
user.setCreate_at(Common.getTime());
userMapper.insertUser(user);
return userMapper.insertUser(user);
return true;
}
@Override
......@@ -68,12 +56,4 @@ public class UserService implements UserMapper {
}
}
@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.Certificate;
import com.asset.mapper.system.CertificateMapper;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/*
* @author xiaol
* @date 2020/03/02
*/
@Service("CertificateService")
public class CertificateService implements CertificateMapper {
@Autowired
CertificateMapper certificateMapper;
@Override
public Certificate getCertificateById(Integer id) {
return certificateMapper.getCertificateById(id);
}
@Override
public Certificate getCertificateByUserId(Integer user_id) {
return certificateMapper.getCertificateByUserId(user_id);
}
@Override
public Page<Certificate> getCertificateList() {
return certificateMapper.getCertificateList();
}
@Override
public boolean insertCertificate(Certificate certificate) {
return certificateMapper.insertCertificate(certificate);
}
@Override
public boolean deleteCertificateById(Integer id) {
return certificateMapper.deleteCertificateById(id);
}
@Override
public boolean updateCertificate(Certificate certificate) {
return certificateMapper.updateCertificate(certificate);
}
}
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);
}
public class CompanyService{
}
......@@ -8,8 +8,8 @@ spring:
#2.数据库连接池
datasource:
username: root
password: 123456
url: jdbc:mysql://152.136.188.17:3306/assets?useUnicode=true&characterEncoding=utf8
password: 861026#Xiaolang
url: jdbc:mysql://152.136.188.17:2303/expert?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
......
......@@ -9,7 +9,7 @@ spring:
datasource:
username: root
password: root
url: jdbc:mysql://152.136.188.17:3306/assets?useUnicode=true&characterEncoding=utf8
url: jdbc:mysql://152.136.188.17:3306/expert?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
......
<?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.CertificateMapper">
<resultMap id="BaseResultMap" type="com.asset.domain.system.Certificate">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_id" jdbcType="VARCHAR" property="user_id"/>
<result column="type" jdbcType="VARCHAR" property="type"/>
<result column="image" jdbcType="VARCHAR" property="image"/>
<result column="create_at" jdbcType="VARCHAR" property="create_at"/>
</resultMap>
<select id="getCertificateById" resultMap="BaseResultMap">
select * from ex_certificate where id=#{id}
</select>
<select id="getCertificateByUserId" resultMap="BaseResultMap">
select * from ex_certificate where user_id = #{user_id}
</select>
<select id="getCertificateList" resultMap="BaseResultMap">
select * from ex_certificate
</select>
<insert id="insertCertificate" parameterType="com.asset.domain.system.Certificate">
insert into ex_certificate(user_id,type,image,create_at) value (#{user_id},#{type},#{image},#{create_at})
</insert>
<delete id="deleteCertificateById" >
delete from ex_user where id=#{id}
</delete>
<update id="updateCertificate" parameterType="com.asset.domain.system.Certificate">
update ex_user set name=#{name},sex=#{sex},mobile=#{mobile},email=#{email},title=#{title} where id=#{id}
</update>
</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.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.system.DisciplineMapper">
<resultMap id="BaseResultMap" type="com.asset.domain.system.Discipline">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
</resultMap>
<select id="getDisciplineById" resultType="com.asset.domain.system.Discipline">
select * from ex_discipline where id = #{id}
</select>
<select id="disciplineList" parameterType="Map" resultMap="BaseResultMap">
select * from ex_discipline
</select>
</mapper>
\ No newline at end of file
......@@ -5,44 +5,49 @@
<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="password" jdbcType="VARCHAR" property="password"/>
<result column="title" jdbcType="VARCHAR" property="title"/>
<result column="idcard" jdbcType="VARCHAR" property="idcard"/>
<result column="card_front" jdbcType="VARCHAR" property="card_front"/>
<result column="email" jdbcType="VARCHAR" property="email"/>
<result column="sex" jdbcType="INTEGER" property="sex"/>
<result column="create_time" jdbcType="VARCHAR" property="create_time"/>
<result column="card_obverse" jdbcType="VARCHAR" property="card_obverse"/>
<result column="mobile" jdbcType="VARCHAR" property="mobile"/>
<result column="school_id" jdbcType="VARCHAR" property="school_id"/>
<result column="discipline_id" jdbcType="VARCHAR" property="discipline_id"/>
<result column="job_id" jdbcType="VARCHAR" property="job_id"/>
<result column="employer" jdbcType="VARCHAR" property="employer"/>
<result column="state" jdbcType="VARCHAR" property="state"/>
<result column="create_at" jdbcType="VARCHAR" property="create_at"/>
</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 * from ex_user where id=#{id}
</select>
<select id="getUserByName" resultMap="BaseResultMap">
select * from user where username = #{username}
select * from ex_user where name = #{name}
</select>
<select id="getUserList" resultMap="BaseResultMap">
select * from user
select * from ex_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 into ex_user(name,password,title,province,card_front,email,sex,card_obverse,mobile,school_id,discipline_id,job_id,employer,create_at,city,county,address,is_expert)
value (#{name},#{password},#{title},#{province},#{card_front},#{email},#{sex},#{card_obverse},#{mobile},#{school_id},#{discipline_id},#{job_id},#{employer},#{create_at},#{city},#{county},#{address},#{is_expert})
</insert>
<delete id="deleteUserById" >
delete from user where id=#{id}
delete from ex_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 ex_user set name=#{name},sex=#{sex},mobile=#{mobile},email=#{email},title=#{title} where id=#{id}
</update>
<update id="updatePassword" parameterType="com.asset.domain.User">
update user set password=#{password} where id=#{id}
update ex_user set password=#{password} where id=#{id}
</update>
</mapper>
\ 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"));
}
}
package com.asset;
import org.junit.Assert;
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 ExpertApplicationTests {
@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();
}
}
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