gpt4 book ai didi

java - Spring Boot REST @RequestParam 未被验证

转载 作者:IT老高 更新时间:2023-10-28 13:51:13 25 4
gpt4 key购买 nike

我尝试了一些来自网络的示例,但无法让 Spring 验证我的查询字符串参数。似乎没有执行 REGEX/失败。

package my.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class MyController {

private static final String VALIDATION_REGEX = "^[0-9]+(,[0-9]+)*$";

@RequestMapping(value = "/my/{id}", method = GET)
public myResonseObject getMyParams(@PathVariable("id") String id,
@Valid @Pattern(regexp = VALIDATION_REGEX)
@RequestParam(value = "myparam", required = true) String myParam) {
// Do Stuff!
}

}

当前行为

PASS - /my/1?myparam=1
PASS - /my/1?myparam=1,2,3
PASS - /my/1?myparam=
PASS - /my/1?myparam=1,bob

期望的行为

PASS - /my/1?myparam=1
PASS - /my/1?myparam=1,2,3
FAIL - /my/1?myparam=
FAIL - /my/1?myparam=1,bob

谢谢

最佳答案

您需要像这样将@Validated 添加到您的类(class)中:

@RestController
@Validated
class Controller {
// ...
}

更新:

您需要正确配置它.. 将此 bean 添加到您的上下文中:

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}

异常处理示例:

@ControllerAdvice
@Component
public class GlobalExceptionHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map handle(MethodArgumentNotValidException exception) {
return error(exception.getBindingResult().getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.toList()));
}


@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map handle(ConstraintViolationException exception) {
return error(exception.getConstraintViolations()
.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList()));
}

private Map error(Object message) {
return Collections.singletonMap("error", message);
}
}

关于java - Spring Boot REST @RequestParam 未被验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614903/

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