title: SpringBoot错误与代码整理 date: 2022-09-02 permalink: /SpringBoot_KENG/ tags: - JAVA - SpringBoot category: 代码整理
<!-- more -->
No serializer found for class com.syes.syes_springboot.entity.Dto.Chat_info and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.syes.syes_springboot.common.Result["data"]->java.util.ArrayList[0])] with root cause
想用DTO,就记住一件事,Lombok
@Autowired@Resource区别
总而言之区别不大
-
@Autowired注解是Spring提供的,而@Resource注解是J2EE本身提供的
-
@Autowird注解默认通过byType方式注入,而@Resource注解默认通过byName方式注入
-
@Autowired注解注入的对象需要在IOC容器中存在,否则需要加上属性required=false,表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错
前端发送数组给后端接收
let piclist = [70, 76, 69] function handleSumbit() { var data = new FormData(); // data.append("piclist", '123456') data.append("title", uploadItem.title.value) data.append("userid", userInfo.userid) data.append("description", uploadItem.description.value) data.append("price", uploadItem.price.value) data.append("piclist", piclist) api.post("/item/uploadAll", data).then(res => { console.log(res) if (res.code == "200") { CommSeccess('操作成功') } } ) }
// 新建item附带图片 @PostMapping("/uploadAll") public Result InsertItem(/*@RequestPart Item item,*/ @RequestParam("title") String title, @RequestParam("userid") String userid, @RequestParam("description") String description, @RequestParam("price") Double price, @RequestParam("piclist") int[] piclist ) { System.out.println(Arrays.toString(piclist)); Item item = new Item(); item.setTitle(title); item.setUserid(userid); item.setDescription(description); item.setPrice(price);
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.36</version> </dependency>
Maven爆红
添加跟springboot一致的版本号,刷新maven然后重启idea
无法自动装配。找不到 'Car' 类型的 Bean。
public class Car { private String brand; private int price; }
添加
@Component @ConfigurationProperties(prefix = "mycar")
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowEr
public Car car (){ return car(); }
把那个括号去掉就好了草
未配置SpringBoot配置注释处理器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
SpringBoot中@ConfigurationProperties()报错
方法一:只需要在这个注解上面添加@Component
就可以了。如下图所示
put delete 在html页面写了,但是无效
spring: mvc: hiddenmethod: filter: enabled: true #开启页面表单的Rest功能
IDEA鼠标拖动变成多行插入
吧insert模式换回来,重启软件
提交没反应
<form action="/save" method="post"> <input type="text" name="username" id=""> <input value="submit" type="button"> </form>
换成button就行,不知道为啥
Missing matrix variable 'low' for method parameter of type Integer
手动开启矩阵变量
thymeleaf超链接变成这样http://localhost:8080/www.hasdsd.cn
没加https
整体样式消失
拦截器拦截了所有请求
@Configuration public class adminWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") // 此时静态资源也被拦截,网站访问静态资源也会出现登录 .excludePathPatterns("/","/login","/static/**"); } }
又一次无视掉了
2022-06-08 13:07:21.865 WARN 2456 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
提交form表单,表单带有图片文件
@PostMapping("/upload") public String uploadForm( @RequestParam("email") String email, @RequestParam("username") String username, @RequestParam("headerImg")MultipartFile headerImg, @RequestParam("photos") MultipartFile [] photos // 自动封装 ){ System.out.println("email:"+email+"username:"+username+"headering:"+headerImg.getSize()+"photos:"+photos.length); return "mainPages"; }
注释换成@RequestMapping
或者,让拦截器拦截了
excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**","/upload/**");
POSTMAN报错
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported]
解决全局跨域问题
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("*") .allowedMethods("*") .maxAge(1800) .allowedOrigins("*"); } }
模糊查询SQL语句
<select id="SearchUser" resultType="com.hasd.springblog.entity.User"> select * from user where (username like ('%' #{username} '%') and email like ('%' #{email} '%')) </select>
数据库静置一段时间后不能请求
Failed to validate connection com.mysql.cj.jdbc.ConnectionImpl@63454f59 (No operations allowed after connection closed.). Possibly consider using a shorter maxLifetime value
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://hasdsd.cn:3307/springblog username: root password: 123456 hikari: minimum-idle: 3 maximum-pool-size: 10 max-lifetime: 30 connection-test-query: SELECT
关于@JsonIginre
注释,添加后不能向后端传送数据或报错没有setter
@JsonIgnore public String getPassword() { return password; } @JsonProperty public void setPassword(String password) { this.password = password; }
如何获取当前列的数据
<el-table-column prop="action" label="操作"> <!--数据操作--> <template slot-scope="info"> <el-button type="success" icon="el-icon-edit" @click="handleEdit(info.row)">编辑 </el-button> <el-button type="danger" icon="el-icon-remove" @click="handleDelete(scope.$index, scope.row)">删除 </el-button> </template> </el-table-column> <script> //操作用户数据-修改 handleEdit(index) { console.log(index) }, </script>
这个info可以随意修改
将数据库的数据导出到excel
// 查询所有 // 导出数据 @GetMapping("/export") public void ExportAll(HttpServletResponse response) throws Exception { List<User> users = userMapper.FindAll(); // 通过工具类创建writer ExcelWriter writer = ExcelUtil.getWriter(true); writer.addHeaderAlias("username", "用户名"); writer.addHeaderAlias("password", "密码"); writer.addHeaderAlias("nickname", "昵称"); writer.addHeaderAlias("email", "邮箱"); writer.addHeaderAlias("phone", "电话"); writer.addHeaderAlias("address", "地址"); writer.addHeaderAlias("createtime", "创建时间"); // 一次性写出内容,使用默认样式,强制输出标题 writer.write(users, true); //设置浏览器相应格式 response.setContentType("application/vnd.ms-excel"); String fileName = URLEncoder.encode("用户信息", "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx"); ServletOutputStream outputStream = response.getOutputStream(); writer.flush(outputStream, true); outputStream.close(); // 关闭writer,释放内存 writer.close(); }
将数据库的数据导入到excel
//导入excel数据 @PostMapping("/import") public Boolean ImportExcel(MultipartFile file) throws Exception { InputStream inputStream = file.getInputStream(); ExcelReader reader = ExcelUtil.getReader(inputStream); List<User> users = reader.readAll(User.class); System.out.println(users); for (User user : users) { userMapper.SaveUser(user); }//万万没想到一个for循环就解决了 return true; }
attempted to return null from a method with a primitive return type (int)
就是在做登录的时候,没找着人,返回个int作为用户id,没找着人就把空塞给Int,就不行,换成User类就可以正常返回空
@PostMapping("/login") public List<UserDto> Login(@RequestBody UserDto userDto) { String username = userDto.getUsername(); String password = userDto.getPassword(); List<UserDto> login = userMapper.login(userDto); return login; }
无法自动装配。找不到 'UserMapper' 类型的 Bean。
加个注解@Mapper
必须在有效 Spring Bean 中定义自动装配成员(@Component|@Service|…)
UserMapper 报空指针
在这个类上加@Component
在拦截器中,UserMapper报空指针,不能请求数据库
//原来代码 @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //拦截请求 registry.addInterceptor(new JwtInterceptor()) .excludePathPatterns("/user/login", "**/register", "/export", "/import") .addPathPatterns("/**"); } }
//修改后代码 @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired JwtInterceptor jwtInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //拦截请求 registry.addInterceptor(jwtInterceptor) .excludePathPatterns("/user/login", "**/register", "/export", "/import") .addPathPatterns("/**"); } }
jwtInterceptor
这个东西要自动装配,不然你一new jwtInterceptor
,就不受spring管辖,里面的方法就找不到userMapper
这个类,也就找不到数据库
MybatisPlus自动加下划线
mybatis-plus: configuration: map-underscore-to-camel-case: false # 禁止大写变小写时自动添加下划线
如果你的拦截器明明放行了,但还是拦截了,那说明请求地址可能错了
你能找出下面哪里写错了吗
一般文件上传与下载
public class Files { @TableId(type = IdType.AUTO) private int id; private String name; private String type; private Long size; private String url; private String md5; private Boolean isDeleted; private String enable; private Date createtime; }
分开
//FileController.java @RestController @RequestMapping("/file") public class FileController { @Resource private FileMapper fileMapper; //获取配置 @Value("/$/{/files/./upload/./path}/") //加斜杠因为博客会认成代码块 private String fileUploadPath; //标记修改删除和修改是否可用 @PutMapping("/put") public int MarkDeleted(@RequestBody Files files) { fileMapper.updateById(files); return 1; } @GetMapping("/id/{id}") public Files getFileById(@PathVariable("id") int id) { Files files = fileMapper.selectById(id); return files; } //分页查询 @GetMapping("/page/p") public Map getUserByPage(@RequestParam("PageNumber") int PageNumber, @RequestParam("PageSize") int PageSize) { int PageStart = (PageNumber - 1) * PageSize; int total = fileMapper.selectTotal(); System.out.println("Pagestart:" + PageStart + " PageSize" + PageSize); List<Files> result = fileMapper.getUserByPage(PageStart, PageSize); Map<String, Object> res = new HashMap<>(); res.put("total", total); res.put("data", result); return res; } @DeleteMapping("/{id}") public int deleteFileById(@PathVariable("id") int id, HttpServletResponse response) { return fileMapper.deleteById(id); } //上传文件 @PostMapping("/upload") public String upload(@RequestParam MultipartFile file) throws IOException { //获取名称 String originalFilename = file.getOriginalFilename(); //获取类型 String type = FileUtil.extName(originalFilename); //获取大小 long size = file.getSize(); //判断配置文件的目录是否存在 File uploadParentFile = new File(fileUploadPath); if (!uploadParentFile.exists()) { uploadParentFile.mkdirs(); } //定义文件唯一标识位 String uuid = IdUtil.fastSimpleUUID(); //UUID,这样方便后续下载 String FileUUID = uuid + StrUtil.DOT + type; //文件路径 UUID+点+文件类型 File uploadFile = new File(fileUploadPath + FileUUID); //下面一大片操作目的是:遇到重复文件时,数据库增加数据,服务器储存不变 String md5; String url; file.transferTo(uploadFile); md5 = SecureUtil.md5(uploadFile); Files dbFiles = getFileByMd5(md5); if (dbFiles != null) { url = dbFiles.getUrl(); uploadFile.delete(); } else { url = "http://192.168.0.123:8080/file/" + FileUUID; } //给数据库添加记录 Files saveFile = new Files(); saveFile.setName(originalFilename); saveFile.setType(type); saveFile.setSize(size); saveFile.setUrl(url); saveFile.setMd5(md5); fileMapper.insert(saveFile); //返回了文件下载链接 return url; } //下载文件 @GetMapping("/{Fileuuid}") public void download(@PathVariable("Fileuuid") String FileUUID, HttpServletResponse response) throws IOException { //根据UUID获取文件 File file = new File(fileUploadPath + FileUUID); //设置输出流的格式 ServletOutputStream os = response.getOutputStream(); //标准表头 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(FileUUID, "UTF-8")); response.setContentType("application/octet-stream"); //读取文件的字节流 os.write(FileUtil.readBytes(file)); os.flush(); os.close(); } //通过MD5查询数据 private Files getFileByMd5(String md5) { QueryWrapper<Files> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("md5", md5); List<Files> files = fileMapper.selectList(queryWrapper); return files.size() == 0 ? null : files.get(0); } }
外置用户头像上传与下载
@TableName("userimg") @Data @ToString @AllArgsConstructor @NoArgsConstructor public class UserimgDto { private int id; private String url; }
分开
//UserimgController.java @RestController @RequestMapping("/userimg") public class UserImgController { @Autowired UserImgMapper userImgMapper; @Autowired FileMapper fileMapper; @Value("/$/{/files/./upload/./path}/") //加斜杠因为博客会认成代码块 private String fileUploadPath; @GetMapping("/url/{id}") public String getUserImg(@PathVariable("id") int id) { UserimgDto userimgDto = userImgMapper.selectById(id); return userimgDto.getUrl(); } //上传文件 @PostMapping("/upload/{userid}") public int upload(@RequestParam MultipartFile file, @PathVariable("userid") int userId) throws IOException { //获取名称 String originalFilename = file.getOriginalFilename(); //获取类型 String type = FileUtil.extName(originalFilename); //获取大小 long size = file.getSize(); //判断配置文件的目录是否存在 File uploadParentFile = new File(fileUploadPath); if (!uploadParentFile.exists()) { uploadParentFile.mkdirs(); } //定义文件唯一标识位 String uuid = IdUtil.fastSimpleUUID(); //UUID,这样方便后续下载 String FileUUID = uuid + StrUtil.DOT + type; //文件路径 UUID+点+文件类型 File uploadFile = new File(fileUploadPath + FileUUID); //下面一大片操作目的是:遇到重复文件时,数据库增加数据,服务器储存不变 String md5; String url; file.transferTo(uploadFile); md5 = SecureUtil.md5(uploadFile); Files dbFiles = getFileByMd5(md5); if (dbFiles != null) { url = dbFiles.getUrl(); uploadFile.delete(); } else { url = "http://192.168.0.123:8080/file/" + FileUUID; } // //给数据库添加记录 // Files saveFile = new Files(); // saveFile.setName(originalFilename); // saveFile.setType(type); // saveFile.setSize(size); // saveFile.setUrl(url); // saveFile.setMd5(md5); // fileMapper.insert(saveFile); // //将URL返回到数据库 UserimgDto userimgDto = new UserimgDto(); userimgDto.setId(userId); userimgDto.setUrl(url); UserimgDto dto = userImgMapper.selectById(userId); System.out.println(dto); if (dto == null) { return userImgMapper.insert(userimgDto); } else { return userImgMapper.updateById(userimgDto); } } //下载文件 @GetMapping("/{Fileuuid}") public void download(@PathVariable("Fileuuid") String FileUUID, HttpServletResponse response) throws IOException { //根据UUID获取文件 File file = new File(fileUploadPath + FileUUID); //设置输出流的格式 ServletOutputStream os = response.getOutputStream(); //标准表头 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(FileUUID, "UTF-8")); response.setContentType("application/octet-stream"); //读取文件的字节流 os.write(FileUtil.readBytes(file)); os.flush(); os.close(); } //通过MD5查询数据 private Files getFileByMd5(String md5) { QueryWrapper<Files> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("md5", md5); List<Files> files = fileMapper.selectList(queryWrapper); return files.size() == 0 ? null : files.get(0); } }
前端发送token,但是后端就是接受不到
//放行OPTIONS请求 String method = request.getMethod(); if ("OPTIONS".equals(method)) { return true; }