Spring Boot REST @RequestParam未经过验证 [英] Spring Boot REST @RequestParam not being Validated
本文介绍了Spring Boot REST @RequestParam未经过验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在网上尝试了很多例子,但是无法让Spring验证我的查询字符串参数。它似乎没有执行REGEX / fail。
I have tried a number of examples from the net and cannot get Spring to validate my query string parameter. It doesn't seem execute the REGEX / fail.
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添加到您的班级,如下所示:
You need add @Validated to your class like this:
@RestController
@Validated
class Controller {
// ...
}
UPDATE :
您需要正确配置它..将此bean添加到您的上下文中:
you need to configure it properly.. add this bean to your context:
@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);
}
}
这篇关于Spring Boot REST @RequestParam未经过验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文