下面我将详细讲解"Spring Boot(五)之跨域、自定义查询及分页"完整攻略.
跨域是指浏览器的安全策略限制了网页从当前源访问另一个源的内容.在 Spring Boot 中,我们可以使用 CorsFilter 实现跨域请求.
首先需要在 pom.xml 中添加依赖:
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-security
然后在 Spring Boot 应用程序中创建一个 CorsFilter:
@Bean
public CorsFilter corsFilter() {
return new CorsFilter(source);
}
这样就完成了跨域请求配置.
在 Spring Boot 中,我们可以使用自定义查询来实现复杂的数据查询.自定义查询通常使用 Query DSL 实现.首先需要在 pom.xml 中添加 Query DSL 相关的依赖:
com.querydsl
querydsl-apt
④④0
provided
com.querydsl
querydsl-jpa
④④0
然后在项目根目录下创建一个 QEntity 类:
@Generated("com.querydsl.codegen.EntitySerializer")
public class QUser extends EntityPathBase {
public final NumberPath id = createNumber("id", Long.class);
public final DateTimePath createTime = createDateTime("createTime", java.util.Date.class);
public QUser(Path extends User> path) {
}
}
然后就可以在 Repository 接口中定义自定义查询方法了:
public interface UserRepository extends JpaRepository, QuerydslPredicateExecutor {
List findAll(Predicate predicate);
}
最后,在 Service 中调用自定义查询方法:
@Service
public class UserService {
public List getUsersByEmail(String email) {
}
}
在 Spring Boot 中,我们可以使用分页功能对数据进行分页查询.首先需要在 pom.xml 中添加依赖:
org.springframework.boot
spring-boot-starter-data-jpa
com.googlecode.concurrentlinkedhashmap
concurrentlinkedhashmap-lru
1.④2
然后在 Controller 中定义分页查询方法:
@GetMapping("/users")
public Page getUsers(@RequestParam(value="page", defaultValue="0") Integer page,
@RequestParam(value="size", defaultValue="10") Integer size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
return userService.getUsers(pageable);
}
然后,在 Service 中执行分页查询:
@Service
public class UserService {
public Page getUsers(Pageable pageable) {
}
}
这样就完成了分页查询的功能.
以上就是土嘎嘎小编为大家整理的Spring Boot_五)之跨域、自定义查询及分页相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!