弹簧控制器@RequestParam中的类型不匹配

时间:2011-03-11 11:26:17

标签: java validation spring-mvc

我正在开发一个spring webservice。我已经创建了一个异常解析器来处理任何异常,以便以适当的格式向客户端发送异常。

正在发送服务层中的异常,并且正在发送自定义消息  问题是如果控制器中的请求参数是数字类型,并且如果用户发送字符串,则发送异常的defaulf消息。但我想发送自定义错误。任何人都可以建议我该怎么做。

2 个答案:

答案 0 :(得分:0)

我认为你需要这样的东西

    @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;
}

答案 1 :(得分:0)

您可以尝试使用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内部,因此您可以从应用程序上下文中获得所有相同的功能。