0

我有以下控制器:

@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正确验证getCarand方法,addCar但它也验证getCars方法。该getCars方法没有{model} @PathVariable,因此对该端点的请求将始终导致RuntimeException.

有什么方法可以排除方法受到 a ControllerAdviceandModelAttribute组合的影响?

4

1 回答 1

0

据我发现,没有真正的方法可以排除方法被@ModelAttributein拦截@ControllerAdvice。但是,您可以将方法参数从更改@PathVariable("model") String modelHttpServletRequest 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.");
  }
}
于 2020-01-28T07:09:37.477 回答