问题描述
假设我具有此控制器映射功能:
@GetMapping("/result")
public Stats result(@RequestParam Integer homeId,@RequestParam Integer awayId)
throws MissingTeamException,InvalidTeamIdExcpetion {
//Validation starts here
int numOfAvailableTeams = teamResource.retrieveAllTeams().size();
if( homeId < 0 || homeId >= numOfAvailableTeams)
throw new InvalidTeamIdExcpetion(homeId);
if(awayId < 0 || awayId >= numOfAvailableTeams)
throw new InvalidTeamIdExcpetion(awayId);
//end of validation
return generateResult(homeId,awayId);
}
您可以看到我正在验证住家和出家证。
除了创建自定义验证器类之外,我还能以更简洁的方式做到这一点吗?
谢谢!
解决方法
通常,在每种情况下,逻辑都应该在服务类(由@Service
标记)中编写,而不是在控制器中编写。因此,您可以使用方法validating()
创建带有验证所需参数的服务类。服务示例:
@Service
public class YourService {
//This variable and constructor are optional because I didn't see your whole code.
//But if you will to create TeamResource field in service,Spring Boot will automatically
//inject teamResource if you have suitable Bean.
private TeamResource teamResource;
public YourService(TeamResource teamResource) {
this.teamResource = teamResource;
}
public TypeOfMethodGenerateResult validate(Integer homeId,Integer awayId) {
int numOfAvailableTeams = teamResource.retrieveAllTeams().size();
if (homeId < 0 || homeId >= numOfAvailableTeams)
throw new InvalidTeamIdExcpetion(homeId);
if(awayId < 0 || awayId >= numOfAvailableTeams)
throw new InvalidTeamIdExcpetion(awayId);
return generateResult(homeId,awayId);
}
}
和控制器:
//Autoinject like in service.
private YourService yourService;
public YourService(YourService yourService) {
this.yourService = yourService;
}
@GetMapping("/result")
public Stats result(@RequestParam Integer homeId,@RequestParam Integer awayId)
throws MissingTeamException,InvalidTeamIdExcpetion {
return yourService.validate(homeId,awayId);
}
,
要验证@RequestParam,可以使用 @Valid 和 @Validated 批注。
@GetMapping("/result")
public String result(@RequestParam @Valid @Size(min = 1) Integer homeId,@RequestParam @Valid @Size(min = 1) Integer awayId)
在类本身上使用 @Validated 。
进口供参考:
导入org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.Size;