提交 5363b069 authored 作者: 孙于凯's avatar 孙于凯

feat:新增easypoi 导出

上级 8161fc01
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EasyCodeTableSetting">
<option name="tableInfoMap">
<map>
<entry key="test.kx_base">
<value>
<TableInfoDTO>
<option name="fullColumn">
<list>
<ColumnInfoDTO>
<option name="comment" value="id" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="id" />
<option name="type" value="java.lang.Integer" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="基地名称" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="baseName" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="级别" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="level" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="基地类型 1自然资源类 2教育科研与重大工程类 3科技场馆类 4企业类 5“三农”类 6其他类 7教育科研类 8公共场所类 9生产设施类 9999为空" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="baseType" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="区域码" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="code" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="地址" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="address" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="联系人" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="person" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="联系电话" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="phone" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="预约电话" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="appointmentPhone" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="认定时间" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="identificationTime" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="推荐单位" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="unit" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="状态 0开放 1关闭" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="status" />
<option name="type" value="java.lang.Integer" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="描述" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="description" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="预留字段" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="reserve" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="经度" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="longitude" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="comment" value="纬度" />
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="latitude" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
</list>
</option>
<option name="name" value="KxBase" />
<option name="preName" value="" />
<option name="saveModelName" value="" />
<option name="savePackageName" value="" />
<option name="savePath" value="" />
<option name="templateGroupName" value="" />
</TableInfoDTO>
</value>
</entry>
<entry key="test.teacher">
<value>
<TableInfoDTO>
<option name="fullColumn">
<list>
<ColumnInfoDTO>
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="id" />
<option name="type" value="java.lang.Integer" />
</ColumnInfoDTO>
<ColumnInfoDTO>
<option name="custom" value="false" />
<option name="ext" value="{}" />
<option name="name" value="ss" />
<option name="type" value="java.lang.String" />
</ColumnInfoDTO>
</list>
</option>
<option name="name" value="Teacher" />
<option name="preName" value="" />
<option name="saveModelName" value="syk-demo" />
<option name="savePackageName" value="" />
<option name="savePath" value="./src/main/java" />
<option name="templateGroupName" value="Default" />
</TableInfoDTO>
</value>
</entry>
</map>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file
......@@ -55,6 +55,16 @@
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!--easy poi依赖-->
<dependency>
<groupId>cn.afterturn</groupId>
......@@ -66,6 +76,17 @@
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<!--easypoi操作-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
......
package com.example.sykdemo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author syk
*/
@Configuration
@MapperScan("com.example.sykdemo.mapper")
public class MybatisPlusConfig {
/**
* 分页查询插件
*
* @return 分页查询插件
*/
@Bean
public MybatisPlusInterceptor mpInterceptor() {
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mpInterceptor;
}
// @Bean(name = "mapperObject")
// public ObjectMapper getObjectMapper() {
// ObjectMapper om = new ObjectMapper();
// JavaTimeModule javaTimeModule = new JavaTimeModule();
// javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
// javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
// om.registerModule(javaTimeModule);return om;
// }
}
\ No newline at end of file
package com.example.sykdemo.controller;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sykdemo.entity.User;
import com.example.sykdemo.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.transform.Result;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
@Api(tags = "测试easypoi导入")
@RestController
@RequestMapping("/aa")
@Slf4j
public class EasyPoiController {
@Resource
private UserMapper userMapper;
@PostMapping ("/testImport")
@PostMapping("/testImport")
@ApiOperation("导入数据库")
public void testImport(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
......@@ -41,6 +47,122 @@ public class EasyPoiController {
List<User> users = ExcelImportUtil.importExcel(file.getInputStream(), User.class, importParams);
for (User user : users) {
userMapper.insert(user);
log.info("成功插入:" + user);
}
}
@PostMapping("/testImport2")
@ApiOperation("导入数据库2 开启校验")
public void testImport2(MultipartFile file) throws Exception {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("上传的文件不能为空");
}
ImportParams importParams = new ImportParams();
//是否开启校验
importParams.setNeedVerfiy(true);
//标题列占得行数
importParams.setTitleRows(0);
//header列占的行数
importParams.setHeadRows(1);
ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(),
User.class, importParams);
//导入成功的数据
List<User> list = result.getList();
//失败结果集
List<User> failList = result.getFailList();
int successful = 0;
int lose = 0;
for (User user : list) {
userMapper.insert(user);
log.info("成功插入:" + user);
successful++;
}
for (User user : failList) {
log.info("失败的数据是" + user);
lose++;
}
log.info("成功插入:" + successful + "条");
log.info("失败:" + lose + "条");
}
// public void test(List<User> rs) throws IOException {
// ExportParams exportParams = new ExportParams();
// exportParams.setSheetName("参与人员信息");
// // 生成workbook 并导出
// Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, rs);
// FileOutputStream outputStream=new FileOutputStream();
// workbook.write(outputStream);
// outputStream.close();
// workbook.close();
// }
@GetMapping("/test")
@ApiOperation("导出user")
public void test(HttpServletResponse response,int pageNum,int pageSize) throws IOException {
Page<User> page = new Page<>(pageNum, pageSize);
Page<User> userPage = userMapper.selectPage(page, null);
List<User> rs = userPage.getRecords();
ExportParams exportParams = new ExportParams();
exportParams.setSheetName("参与人员信息");
// 生成 workbook 并导出
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, rs);
try {
OutputStream outputStream = response.getOutputStream();
// 下面几行是为了解决文件名乱码的问题
response.setHeader("Content-Disposition", "attachment;filename=" + new String(UUID.randomUUID().toString().getBytes(), StandardCharsets.UTF_8) + ".xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//关闭缓存
response.setHeader("Pragma", "no-cache");
//关闭缓存
response.setHeader("Cache-Control", "no-cache");
//为了让浏览器不要缓存页面,也可以利用Expires实体报关域,设置为0
response.setDateHeader("Expires", 0);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@PostMapping("/testImport3")
@ApiOperation("导入数据库3 开启校验")
public void testImport3(MultipartFile file) throws Exception {
try {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("上传的文件不能为空");
}
ImportParams importParams = new ImportParams();
// 是否开启校验
importParams.setNeedVerfiy(true);
// 标题列占得行数
importParams.setTitleRows(0);
// header列占的行数
importParams.setHeadRows(1);
ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(),
User.class, importParams);
// 导入成功的数据
List<User> list = result.getList();
// 失败结果集
List<User> failList = result.getFailList();
int successful = 0;
int failed = 0;
for (User user : list) {
userMapper.insert(user);
log.info("成功插入:" + user);
successful++;
}
for (User user : failList) {
log.info("导入文件中存在无法插入的数据:" + user);
failed++;
}
log.info("成功插入:" + successful + "条");
log.info("失败:" + failed + "条");
} catch (ExcelImportException e) {
log.info("导入失败的数据是");
}
}
}
......@@ -2,18 +2,29 @@ package com.example.sykdemo.entity;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import lombok.NonNull;
import javax.print.attribute.standard.MediaSize;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
@Excel(name = "基地")
// @NotNull(message="基地不能为空")
@NotNull(message="基地不能为空")
private String base;
@Excel(name="姓名")
private String name;
@Excel(name="性别")
private String sex;
@Excel(name="生日",format = "yyyy-MM-dd")
private Date bir;
@Excel(name="年龄",format = "yyyy-MM-dd")
private Integer age;
}
package com.example.sykdemo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class sykdemo {
private Integer id;
private String name;
private String iphone;
}
package com.example.sykdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.sykdemo.entity.sykdemo;
import org.mapstruct.Mapper;
@Mapper
public interface SykdemoMapper extends BaseMapper<sykdemo> {
}
package com.example.sykdemo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.sykdemo.entity.sykdemo;
public interface SykdemoService extends IService<sykdemo> {
sykdemo addSykDemo(sykdemo sykdemo);
}
package com.example.sykdemo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sykdemo.entity.sykdemo;
import com.example.sykdemo.mapper.SykdemoMapper;
import com.example.sykdemo.service.SykdemoService;
import com.example.sykdemo.util.Sm4Util;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class SykdemoServiceImpl extends ServiceImpl<SykdemoMapper, sykdemo> implements SykdemoService {
@Resource
private SykdemoMapper sykdemoMapper;
@Override
public sykdemo addSykDemo(sykdemo sykdemo) {
// sykdemo.setName(Sm4Util.);
return null;
}
}
......@@ -9,4 +9,5 @@ import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
package com.example.sykdemo.util;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
/**
* SM4算法目前只支持128位(即密钥16字节)
*
* @author ozoz
* @date 2023/8/23
**/
public class Sm4Util {
private static final String ALGORITHM_NAME = "SM4";
private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
/**
* SM4算法目前只支持128位(即密钥16字节)
*/
private static final int DEFAULT_KEY_SIZE = 128;
private static Object lock = new Object();
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* 加密
*
* @param data 数据
* @param key 秘钥
* @return 密文
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM_NAME);
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING,
BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
public static String encrypt(String data, String key) throws Exception {
if (data == null) {
return null;
}
byte[] encrypt = Sm4Util.encrypt(data.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8));
//转换为标准的Base64字符串
return Base64.encodeBase64String(encrypt);
}
/**
* 解密
*
* @param data 数据
* @param key 秘钥
* @return 明文
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM_NAME);
Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING,
BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
/**
* 解密
*
* @param data 数据
* @param key 密钥
* @return 明文
* @throws Exception e
*/
public static String decrypt(String data, String key) throws Exception {
if (data == null) {
return null;
}
byte[] decryptBytes = Base64.decodeBase64(data);
byte[] decrypt = Sm4Util.decrypt(decryptBytes, key.getBytes("UTF-8"));
return new String(decrypt);
}
public static void main(String[] args) throws Exception {
/**
* SM4算法目前只支持128位(即密钥16字节)
*/
// String key = "nXwqj7JVe@czbD4E";
// String key = "tykj2023tykj2023";
String key = "sykkjhasd123fr12";
System.out.println("key:" + key);
String data = "李涛";
System.out.println(encrypt(data, key));
/**
* 加密
*/
byte[] encrypt = Sm4Util.encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"));
//转换为标准的Base64字符串
String encryptStr = Base64.encodeBase64String(encrypt);
System.out.println("加密:" + encryptStr);
/**
* 解密
*/
byte[] decryptBytes = Base64.decodeBase64(encryptStr);
byte[] decrypt = Sm4Util.decrypt(decryptBytes, key.getBytes("UTF-8"));
String decryptStr = new String(decrypt);
System.out.println("解密:" + decryptStr);
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论