[英]Spring Rest API - spurious/not requested parameters strategy
根據此討論- “ RESTful API-在請求中傳遞虛假/未請求的參數時的正確行為” ,我們不應忽略未請求的參數,但如何在所有端點上處理這種情況?
例如,此端點:
@RequestMapping(value = "/transactions/",
method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public RestResultSupport getCommandsById(@PathVariable("id") String id) throws IOException {
validateId(id);
....
return result;
}
對於2個不同的請求,我們將獲得相同的結果:
curl localhost:8080/?id=1200
和
curl localhost:8080/?id=1200&unknown=incorrect
如果我們設想應該在20個端點上處理這種情況,那么如何簡化代碼? Spring是否為此提供一些工具?
我發現只有一種方法可以實現-實現HandlerInterceptor。
請看一個例子:
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
Set<String> innerParams = request.getParameterMap().keySet();
Set<String> describedParams = new HashSet<>();
for (MethodParameter methodParameter : ((HandlerMethod) handler).getMethodParameters()) {
if (methodParameter.hasParameterAnnotation(RequestParam.class)) {
RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
describedParams.add(requestParam.name());
}
}
for (String inputRequestParam : innerParams) {
if (!describedParams.contains(inputRequestParam)) {
throw new BadDataException("Please provide valid request paramaters. [ Valid request parameters - " + describedParams + " ]");
}
}
return true;
}
... empty other required methods ...
}
代碼分析所需的參數,如果未知,它將拋出RuntimeException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.