Springboot 练习2 (续JavaWeb笔记_10)
1. 查询
1.1.1 分页查询
1.1.2 创建JavaBean封装结果
- 由于返回结果为两个,需新建一个Bean来封装结返回果
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean {
private Long count;
private List<Account> accounts;
}
1.1.3 代码实现
- 持久层:在AccountMapper接口中声明一下方法
@Select("select * from mybatis.account limit #{start}, #{size}")
List<Account> findALlOfPagination(int start, Integer size);
@Select("select count(*) from mybatis.account")
Long count();
- 服务层:在AccountService接口声明方法
- 在AccountServiceImpl类实现方法
@Override
public PageBean findALlOfPagination(Integer start, Integer size) {
PageBean pageBean = new PageBean();
pageBean.setCount(am.count());
pageBean.setAccounts(am.findALlOfPagination((start - 1) * size, size));
return pageBean;
}
@RequestMapping("/accounts")
Result findALlOfPagination(Integer start, Integer size){
PageBean pb = as.findALlOfPagination(start, size);
return Result.success(pb);
}
- 查询结果如下:
1.2使用PageHelper分页查询
1.2.1 导入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
1.2.2 在服务层创建对象
@Override
public PageBean findALlOfPagination(Integer start, Integer size) {
PageHelper.startPage(start, size);
Page<Account> all = am.findAll();
return new PageBean(all.getTotal(), all.getResult());
}
1. 文件上传
1.1 文件上传到本地
1.1.1 前端页码
<form action="/upload" method="post" enctype="multipart/form-data">
姓名: <input type="text" name="username"><br>
年龄: <input type="text" name="age"><br>
头像: <input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
1.1.2 代码实现
@RestController
public class Upload {
@RequestMapping("/upload")
Result upload(MultipartFile file) throws IOException {
File path = new File("D:\\" + file.getOriginalFilename());
file.transferTo(path);
return Result.success();
}
}