@ApiOperation(value = "根据名称和年龄段查找用户") // 修改API文档描述 @ApiImplicitParams(value = { @ApiImplicitParam(name = "名称", value = "年龄段", dataTypeClass = String.class) }) @GetMapping ("/find") public UserInfo findDeviceInfo(@RequestParam String name,@RequestParam int age) throws Exception { return deviceService.findUserInfoByIdAndName(age, name); }通过控制层代码编写出业务层代码,如果name为空则提示用户名不能为空,如果age为空则提示年龄不能为空,且年龄必须大于18且小于120,如果超限则提示输入有误,请核对后重新输入
时间: 2024-02-25 07:57:07 浏览: 14
根据你提供的控制层代码,我们可以在业务层代码中添加相应的参数校验逻辑,如下所示:
```java
@Service
public class DeviceService {
@Autowired
private UserRepository userRepository;
public UserInfo findUserInfoByIdAndName(int age, String name) throws Exception {
if (StringUtils.isEmpty(name)) {
throw new Exception("用户名不能为空");
}
if (age == null) {
throw new Exception("年龄不能为空");
}
if (age < 18 || age > 120) {
throw new Exception("年龄必须大于18且小于120");
}
UserInfo userInfo = userRepository.findByNameAndAge(name, age);
if (userInfo == null) {
throw new Exception("未找到符合条件的用户信息");
}
return userInfo;
}
}
```
在业务层代码中,我们首先判断用户名和年龄是否为空,如果为空,则抛出相应的异常。接着,我们判断年龄是否符合要求,如果不符合要求,则同样抛出相应的异常。最后,我们调用 `UserRepository` 中的 `findByNameAndAge` 方法来获取用户信息,如果找不到符合条件的用户信息,则同样抛出相应的异常。
这样,我们就可以根据控制层代码编写出带有参数校验逻辑的业务层代码了。