gpt4 book ai didi

java - 从 @RestControllerAdvice 中的 @ModelAttribute 中排除方法

转载 作者:行者123 更新时间:2023-12-01 18:44:49 25 4
gpt4 key购买 nike

我有以下 Controller :

@RestController
@RequestMapping("/api/{brand}"
public class CarController {

@GetMapping
public List<Car> getCars(@PathVariable("brand") String brand) {
// Some implementation
}

@GetMapping("/{model}")
public Car getCar(@PathVariable("model") String model) {
// Some implementation
}

@PostMapping("/{model}")
public Car addCar(@PathVariable("model") String model), @RequestBody Car car) {
// Some implementation
}
}

以及以下RestControllerAdvice:

@RestControllerAdvice(assignableTypes = {CarController.class})
public class InterceptModelPathParameterControllerAdvice {

@Autowired
CarService carService;

@ModelAttribute
public void validateModel(@PathVariable("model") String model) {
if (!carService.isSupportedModel(model)) throw new RuntimeException("This model is not supprted by this application.");
}
}

validateModel 正确验证 getCaraddCar 方法,但它也验证 getCars 方法。 getCars 方法没有 {model} @PathVariable,因此对此端点的请求将始终导致 RuntimeException

是否有任何方法可以排除方法受到 ControllerAdviceModelAttribute 组合的影响?

最佳答案

据我所知,没有真正的方法可以排除 @ControllerAdvice 中的 @ModelAttribute 拦截方法>。但是,您可以将方法参数从 @PathVariable("model") String model 更改为 HttpServletRequest request 并更改实现,如下所示:

@ModelAttribute
public void validateModel(HttpServletRequest) {
Map<String, String> requestAttributes = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (requestAttributes.containsKey("model") {
String model = requestAttributes.get("model");
if (!carService.isSupportedModel(model)) throw new RuntimeException("This model is not supprted by this application.");
}
}

关于java - 从 @RestControllerAdvice 中的 @ModelAttribute 中排除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59860210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com