在 spring boot 中实现 rest 接口的条件筛选,最直接且符合规范的做法是使用 @requestparam 接收前端传递的查询参数,并在 service 层通过 specification 或 jpacriteriabuilder 动态构建查询条件。如果传入的参数为空,则忽略该条件以返回全量数据;如果存在值,则将其加入 where 子句进行过滤。这种方式避免了硬编码 sql,同时保证了接口的灵活性和安全性。

如何定义支持多条件的 Controller 接口
Controller 层负责暴露 HTTP 端点并接收请求参数。我们需要定义一个 GET 请求方法,使用 @GetMapping 注解指定路径,并使用 @RequestParam 标注各个筛选字段。为了处理可选参数,可以为 @RequestParam 设置 required = false 并提供默认值(如空字符串)。这样当客户端不传参时,后端能正常接收 null 或空值,进而由后续逻辑决定是跳过筛选还是执行特定匹配。

package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public Page<User> getUsers(
@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
// 调用 Service 层进行动态查询
return userService.findUsers(name, age, PageRequest.of(page, size));
}
}
上述代码定义了一个 /api/users 接口。name 和 age 是可选的筛选条件。page 和 size 用于分页,默认值为第 0 页,每页 10 条。当用户访问 /api/users?name=John&age=30 时,控制器将这两个值传递给服务层。如果只访问 /api/users,则 name 和 age 为 null,服务层应返回所有用户。这种设计确保了接口既能做精确筛选,也能做全量获取。
Service 层如何实现动态 JPA Specification 查询
Service 层的核心逻辑在于根据传入的参数构建 Specification。我们使用 JPA 的 Specification 接口,它允许我们在运行时动态组装 WHERE 子句。通过创建一个内部类或静态方法来实现 toPredicate 方法,检查每个参数是否为 null 或空字符串。如果不为空,则添加对应的 CriteriaQuery 谓词;如果为空,则返回 null 表示该条件不参与过滤。最终将这些谓词组合成 AND 关系。

package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Page<User> findUsers(String name, Integer age, Pageable pageable) {
Specification<User> spec = buildSpecification(name, age);
return userRepository.findAll(spec, pageable);
}
private Specification<User> buildSpecification(String name, Integer age) {
return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
List<pre class="brush:php;toolbar:false;"dicate> predicates = new ArrayList<>();
if (StringUtils.hasText(name)) {
predicates.add(cb.like(root.get("name"), "%" + name + "%"));
}
if (age != null) {
predicates.add(cb.equal(root.get("age"), age));
}
return cb.and(predicates.toArray(new Predicate[0]));
};
}
}
这段代码展示了 buildSpecification 方法的实现。它首先创建一个空的 Predicate 列表。然后检查 name 是否包含文本,如果包含,则使用 cb.like 添加模糊匹配条件。接着检查 age 是否为 null,如果不为 null,则使用 cb.equal 添加精确匹配条件。最后,使用 cb.and 将所有谓词组合起来。如果两个参数都为空,返回的谓词数组为空,JPA 会生成不带 WHERE 子句的查询,从而返回所有记录。这种方法高效且类型安全,避免了 SQL 注入风险。
当输入参数包含特殊字符或空值时如何处理
在实际使用中,用户可能输入包含 SQL 特殊字符的字符串,或者传递空字符串而非 null。Spring 的 StringUtils.hasText() 方法可以很好地处理空字符串和空白字符的情况,确保只有非空内容才触发筛选。对于特殊字符,由于使用的是 JPA Criteria API,参数会被自动转义为预编译语句的参数,因此无需手动处理转义问题。然而,如果业务逻辑要求对空字符串进行特殊处理(例如视为“无筛选”),则需要在 Controller 或 Service 层显式判断。此外,如果希望区分“未传参”和“传了空值”,可以使用 @RequestParam 的 defaultValue 属性,但通常推荐统一将空值视为无筛选条件,以保持接口行为的一致性。


















