hawcat
文章20
标签28
分类8

文章分类

文章归档

Springboot - 文件上传、工具、异常处理

Springboot - 文件上传、工具、异常处理

文件上传Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@PostMapping("upload")
@ResponseBody
public Result upload(@RequestParam MultipartFile file) throws BizException{
//文件名
final String filename = file.getOriginalFilename();
//保存
try {
file.transferTo(new File("本地或者网络路径",filename));
} catch (IOException e) {
throw new BizException("文件上传失败",e);
}
//C:/Users/yht11/Desktop/upload ==>127.0.0.1/head 目录地址映射
return Result.success("文件上传成功", "/head/" + filename);

}

Mybatis-Plus代码快速生成工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CodeUtil {
public static void main(String[] args){
FastAutoGenerator.create("jdbc:mysql:///vote", "root", "**")
.globalConfig(builder -> {
builder.author("hawcat") // 设置作者
//.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("路径"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("cn.hawcat") // 设置父包名
.moduleName("模块名") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "路径")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder//.addInclude("t_simple") // 设置需要生成的表名
.addTablePrefix("tp_"); // 设置过滤表前缀
})
//.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();


}

常用异常类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Utils {

//判断空对象,空字符串,空集合方法
public static boolean isEmpty(Object obj){
if(obj == null){
return true;

}else if(obj instanceof String){
String s = (String) obj;
return s.trim().isEmpty();

}else if(obj instanceof Collection){
Collection c = (Collection) obj;
return c.isEmpty();

}else if(obj instanceof Map){
Map c = (Map) obj;
return c.isEmpty();
}
return false;
}

//用户检查bool值是否为true,如果是true则抛出异常
public static void check(boolean bool,String msg) throws BizException{
if(bool){
throw new BizException(msg);
}
}

//判断obj是否为空,如果是空 则抛出异常
public static void checkEmpty(Object obj,String msg) throws BizException{
check(isEmpty(obj),msg);
}
}

自定义业务异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//自定义业务异常
public class BizException extends Exception{
public BizException() {
}

public BizException(String message) {
super(message);
}

public BizException(String message, Throwable cause) {
super(message, cause);
}

public BizException(Throwable cause) {
super(cause);
}

public BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}


自我学习记录用,可能代码有不规范的地方。

:D 获取中...

本文作者:hawcat
本文链接:https://hawcat.cn/2023/02/10/Spring3/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可
×