@RequestMapping(value = "/test")
@ResponseBody
public Object test(@RequestParam("latitude") String latitude,
@RequestParam("longitude") String longitude) {
}
在这种情况下,如果纬度不为空,则经度必须不为空。
如何验证相关的请求参数? 是否有开箱即用的解决方案,或手动验证?
答案 0 :(得分:2)
如果您使用的是最新版本的弹簧,则会有注释@Validated
。
通过此注释,我们可以同时验证@RequestParam
和@PathVariable
最值得注意的是,@Valid
用于验证RequestBody
会引发异常 MethodArgumentNotValidException
@Validated
抛出 ConstraintViolationException
因为两个例外属于不同类型,您必须使用@ExceptionHandler
以不同方式处理它们,如下所示: -
@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleConstraintViolationException(ConstraintViolationException e) {
// your code here to handle the exceptions accordingly
}
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
// your code here to handle the exceptions accordingly
}
答案 1 :(得分:0)
这是一种方法:
@RequestParam
的情况下进行类型参数绑定LongLatException
下方创建自定义例外,并将其直接绑定到您喜欢的 HTTP错误代码(HttpStatus.BAD_REQUEST
下方完全正常工作1个文件代码:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping("/test")
@ResponseBody
public String test(LongLat longLat) {
if(isNotValid(longLat)) {
throw new LongLatException();
}
return "latitude: "+longLat.getLatitude() + ", longtitude: " + longLat.getLongitude();
}
private boolean isNotValid(LongLat longLat) {
return (longLat.getLongitude() == null && longLat.getLatitude() != null) ||
(longLat.getLongitude() == null && longLat.getLatitude() == null);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
static class LongLatException extends RuntimeException {
public LongLatException() {
super("Longitude and Latitude params either need to be both present or empty");
}
}
static class LongLat {
private final String latitude;
private final String longitude;
public LongLat(String latitude, String longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
@Override
public String toString() {
String sb = "LongLat{" + "latitude='" + latitude + '\'' +
", longitude='" + longitude + '\'' +
'}';
return sb;
}
}
}