Boot常见错误与代码整理

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;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一种用于构建独立的、基于Java的Web应用程序的开源框架。医疗产品源代码是指用Spring Boot框架编写的用于实现医疗业务功能的软件代码。 使用Spring Boot框架开发医疗产品源代码有以下优点: 1. 快速开发:Spring Boot提供了一系列开箱即用的功能,如自动配置、快速启动、适用于生产环境的默认配置等。这些功能可以大大提高开发效率并缩短开发周期。 2. 易于扩展:Spring Boot框架采用模块化设计,开发人员可以方便地添加、替换或删除组件,以满足医疗产品不断变化的需求。同时,Spring Boot与Spring系列框架完美集成,可以充分利用Spring生态系统中丰富的功能和第三方库。 3. 高度可测试性:Spring Boot应用程序采用松耦合的设计原则和依赖注入的方式组织代码,使得单元测试和集成测试变得更加容易。可以在不启动整个应用程序的情况下轻松测试应用程序的各个组件。 4. 安全性:Spring Boot提供了一系列安全性功能,例如身份验证、授权、加密和访问控制等,可以用于保护医疗产品的敏感信息和保护用户数据的安全。 5. 可维护性:Spring Boot框架提供了一种结构化的开发方式,使得应用程序代码易于理解、维护和优化。通过良好的代码组织和注释,开发人员可以快速定位和修改bug,同时也可以减少代码的重复性和冗余。 总之,使用Spring Boot框架开发医疗产品源代码可以提高开发效率、可扩展性、可测试性、安全性和可维护性,满足医疗产品不断变化的需求,并为医疗行业提供更稳定和可靠的软件解决方案。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值