[英]Type mismatch in spring controllers @RequestParam
我正在從事Spring Web服務。 我創建了一個用於處理所有異常的異常解析器,以便以正確的格式將異常發送到客戶端。
服務層中捕獲了異常,並且正在發送自定義消息。
問題是,如果控制器中的請求參數為數字類型,並且如果用戶發送了字符串,則將發送異常的defaulf消息。 但我想發送自定義錯誤。 任何人都可以建議我該怎么做。
我想你需要這樣的東西
@RequestMapping(value = "/happy}", method = RequestMethod.POST)
public String happy(@RequestParam(value = "somevalue") int number) {
// implement your flow
return null;
}
@RequestMapping(value = "/happy}", method = RequestMethod.POST)
public String unhappy(@RequestParam(value = "somevalue") String string) {
// send a custom error message to the user to use a number instead of a String
return null;
}
您可以嘗試使用Spring Handler Interceptor ,從請求本身中將參數提取為字符串,然后檢查其是否為數字。 您可以為每種情況設置一個攔截器,然后僅在那些端點上進行監視(簡單但更多的類),或者對其進行泛化以驗證請求中所有端點的參數。
每個案例一個:
public class IntTypeCheckInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String myIntString = request.getParameter("myInt");
Pattern intPattern = Pattern.compile("[0-9]+");
Matcher intMatcher = intPattern.matcher(myIntString);
//I *think* this does the whole input
if(!intMatcher.matches()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return false; //false tells spring to stop processing and returns to the client
}
return true; //true tells spring to continue as normal
}
}
配置:
@Override
public void addInterceptors(InterceptorRegistry registry) {
//with this only do where the request parameter is the same name and expected to be an int
registry.addInterceptor(new IntTypeCheckInterceptor()).paths("/your-intpath", "your-intpath2");
}
另一種方法涉及檢查處理程序是HandlerMethod,拉出參數名稱和類型,並檢查每個參數。
過濾器也應該起作用。 我對攔截器更加熟悉,它位於Spring內部,因此您可以從應用程序上下文中獲得所有相同的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.