spring boot内置web服务器默认是tomcat,但是并不是一定要用它,spring boot不止整合了这一个
我们在启动的时候可以看到,日志输出是使用的tomcat
这是由于导入的web包会自动默认加载tamcat
如果不用tomcat,此时需要将pom依赖修改,将web服务器改成undertow
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-undertow
在启动项目即可
除了内置web的修改,spring boot同样可以修改mvc的配置,前面我们配置了myatisplus,mvc和它一样也是通过类来修改配置
package com.wy.scjg.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
}
不同的是mvc的配置继承了一个接口,通过这个接口我们可以设置前端相关的一些配置,这里我们以自定义静态资源配置为例
idea快捷键ctrl+o,打开父类方法界面,我们可以看到很多方法
我们重写其中的获取静态资源方法
package com.wy.scjg.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//自定义静态资源存放地址
registry.addResourceHandler("/imgs
@RequestMapping("/add")
@ResponseBody
public boolean add(User user,MultipartFile file,MultipartFile[] files){
try {
//证件照的处理
if (file != null) {
//判断文件不为空
if (!file.isEmpty()) {
//获取文件名称
String originalFilename = file.getOriginalFilename();
//新文件名称
String fileName = UUID.randomUUID() + "_" + originalFilename;
//创建新文件对象
File destFile = new File("D://imgs", fileName);
//判断目标文件存在否
if (!destFile.getParentFile().exists()) {
//创建目录
destFile.mkdirs();
}
//执行拷贝过程
file.transferTo(destFile);
//保存文件的文件名
user.setZp("http://localhost:91/imgs/"+fileName);
}
}
//任意张个人照的处理
if(files!=null ){
//准备一个字符串缓冲区,保存任意张个人照路径
StringBuffer grzPaths = new StringBuffer();
for(MultipartFile t:files){
if(!t.isEmpty()){
//获取文件名称
String originalFilename = t.getOriginalFilename();
//新文件名称
String fileName = UUID.randomUUID() + "_" + originalFilename;
//创建新文件对象
File destFile = new File("D://imgs", fileName);
//判断目标文件存在否
if (!destFile.getParentFile().exists()) {
//创建目录
destFile.mkdirs();
}
//执行拷贝过程
t.transferTo(destFile);
//拼接文件的文件名,用逗号隔开
grzPaths.append("http://localhost:91/imgs/"+fileName+",");
}
}
//保存所有个人照路径
user.setGrz(grzPaths.delete(grzPaths.length()-1,grzPaths.length()).toString());
grzPaths.delete(0,grzPaths.length());
}
}catch (IOException io){
io.getMessage();
}
return userService.save(user);
}
前端列表页面添加图片的展示,这里注意只展示工作照,多张的个人照留给大家扩展自己写
此外将添加页面的ajax成功回调函数改一下,添加成功后去列表页面
// ajax请求
$.ajax({
type: "POST",
url: "/user/add",
data: formData,
processData: false,
contentType: false,
success: function (data) {
alert("文件接收成功")
window.location.href="/user/list";
},
error: function (e) {
alert("文件接收失败");
}
});
运行程序,添加用户查看效果
这个时候我要解释一点,有人觉得数据库可以减少存储的父路径,将父路径写到前端,大家怎么方便怎么来
如果细心的朋友会发现,在邮箱地址传递上,发生了意外,@变成了%40,传向后台发生转义,这个事网上很多办法都是时灵时不灵的,我这里试了几个方法没有能够生效的,最后在后台用字符串转换了一下
user.setEmail(user.getEmail().replaceAll("%40","@"));



