springboot其他

/ springboot / 2 条评论 / 1277浏览

单元测试

@SpringBootTest:标识在测试类上
@Test:标识测试方法
@Autowired:从spring容器中取出bean注入

@SpringBootTest
class How2jApplicationTests {

    @Autowired
    private CategoryDAO categoryDAO;

    /**
     * 查询所有的类别数据
     */
    @Test
    public void fun1() {
        List<Category> all = categoryDAO.findAll();
        System.out.println(all);
    }
}

jpa条件查询

public interface CategoryDAO extends JpaRepository<Category, Integer>{

    /**
     * 根据名称查询类别
     * @param name
     * @return
     */
    public List<Category> findByName(String name);

    /**
     * 根据名称模糊查询
     * @param name
     * @return
     */
    public List<Category> findByNameLike(String name);

    /**
     * 根据名称查询类别并排序
     * @param name
     * @param id
     * @return
     */
    public List<Category> findByNameLikeAndIdGreaterThanOrderByNameAsc(String name, Integer id);
}

对照表

文件上传

前端页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<form action="/upload/file" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="col-sm-3 control-label"></div>
        <div class="col-sm-1 control-label">选择文件</div>
        <div class="col-sm-3">
            <div class="input-group">
                <input id='location' class="form-control" onclick="$('#i-file').click();">
                <label class="input-group-btn">
                    <input type="button" id="i-check" value="浏览文件" class="btn btn-primary" onclick="$('#i-file').click();">
                </label>
            </div>
        </div>
        <input type="file" name="file" id='i-file'  accept="*" onchange="$('#location').val($('#i-file').val());" style="display: none">
        <input class="btn btn-default" type="submit" value="上传">
    </div>
</form>
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>

controller文件上传控制类

@ResponseBody
@RequestMapping(value = "/file", method = RequestMethod.POST)
public Result file(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
    try {
        //新的文件名称:时间戳 + 上传文件的后缀
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        //设置文件保存的路径
        String destFileName = "f:/uploaded" + File.separator + fileName;
        //创建文件目录
        File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        //复制文件到指定位置
        file.transferTo(destFile);
        //返回文件名称
        return ResultUtil.ok(fileName);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return ResultUtil.error(500, "上传失败");
    } catch (IOException e) {
        e.printStackTrace();
        return ResultUtil.error(500, "上传失败");
    }
}

修改yml配置文件(spring默认上限很小)

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB

文件下载

    @RequestMapping("/download/{fileName}")
    public Result testDownload(HttpServletResponse response, @PathVariable String fileName) {
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(fileName);
        //设置为png格式的文件
        response.setHeader("content-type", type);
        response.setContentType("application/octet-stream");
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File("f:/uploaded/" + fileName)));
            int read = bis.read(buff);
            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch (IOException e) {
            log.error("下载失败:", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("下载成功:{}", fileName);
        return null;
    }

大文件下载

    @GetMapping("/download")
    public ResponseEntity<StreamingResponseBody> downloadStudentWork() throws Exception {
        // 1.腾讯云cos文件下载(下载到临时文件夹)
        String zipDownloadDir = "D:\\rh_audit\\backend\\upload\\downloadDir-1713412564343.zip";
        String exportFileName = "test.zip";
        // 2.设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        exportFileName = URLEncoder.encode(exportFileName, StandardCharsets.UTF_8.toString());
        headers.setContentDispositionFormData("attachment", exportFileName);
        String finalExportFileName = exportFileName;
        StreamingResponseBody responseBody = outputStream -> {
            try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
                // 文件读取和压缩
                InputStream inputStream = new FileInputStream(zipDownloadDir);
                ZipEntry zipEntry = new ZipEntry(finalExportFileName);
                zipOut.putNextEntry(zipEntry);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    zipOut.write(buffer, 0, bytesRead);
                }
                zipOut.closeEntry();
                inputStream.close();
                // 添加更多附件,如果有的话
                zipOut.finish();
            } catch (IOException e) {
                // 处理异常
                e.printStackTrace();
            }
        };
        return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
    }

Restful风格

同一个url不同的请求方式(get、post、put、delte)
@PathVariable:获取url中的占位参数

1. 资源名称用复数,而非单数。
即使用 /categories 而不是用 /category

2. CRUD 分别对应:
增加: post
删除: delete
修改: put
查询: get

3. id 参数的传递都用 /id方式。
如编辑和修改:
/categories/123

4. 其他参数采用?name=value的形式
如分页参数 /categories?start=5

5. 返回数据
查询多个返回 json 数组
增加,查询一个,修改 都返回当前 json 数组
删除 返回空
    /**
     * 分页数据集合
     * @param start
     * @param size
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping("/categories")
    public Result listCategory(@RequestParam(value = "start", defaultValue = "0")int start,
                               @RequestParam(value = "size", defaultValue = "5")int size)throws Exception{
        //语法糖 防止start小于0
        start = start<0?0:start;
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pageRequest = PageRequest.of(start, size, sort);
        Page<Category> page = categoryDAO.findAll(pageRequest);
        return ResultUtil.ok(page);
    }

    /**
     * 添加操作
     * @param category
     * @return
     */
    @ResponseBody
    @PostMapping("/categories")
    public Result addtCg(Category category){
        Category save = categoryDAO.save(category);
        return  ResultUtil.ok(save);
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @ResponseBody
    @DeleteMapping("/categories/{id}")
    public Result deleteCg(@PathVariable Integer id){
        categoryDAO.deleteById(id);
        return ResultUtil.ok(null);
    }

    /**
     * 更新操作
     * @param category
     * @return
     */
    @ResponseBody
    @PutMapping("/categories")
    public Result updateCg(Category category){
        Category save = categoryDAO.save(category);
        return ResultUtil.ok(save);
    }

JSON

@RequestBody:接受json数据封装到指定对象中

@PutMapping("/category")
public void addCategory(@RequestBody Category category) throws Exception {
    System.out.println("springboot接受到浏览器以JSON格式提交的数据:"+category);
}

@ResponseBody:返回json数据

@ResponseBody
@PostMapping("/categories")
public Result addtCg(Category category){
    Category save = categoryDAO.save(category);
    return  ResultUtil.ok(save);
}

@JsonIgnoreProperties:自定义实体类转换json的过程

@Entity
@Table(name = "category_")
@Data
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;
}