美文网首页
SpringMVC分页参数自动注入

SpringMVC分页参数自动注入

作者: 黄枣颖 | 来源:发表于2019-12-26 17:39 被阅读0次

    通过实现HandlerMethodArgumentResolver接口,帮助分页查询接口自动注入分页参数,同时可以进行入参校验,自动赋予默认值

    @Slf4j
    @Component
    public class PaginationArgumentResolver implements HandlerMethodArgumentResolver {
        @Override
        public boolean supportsParameter(MethodParameter methodParameter) {
            String paramName = methodParameter.getParameterName();
            //参数类型是不是整型,并且参数名称是page
            return Integer.class.isAssignableFrom(methodParameter.getParameterType())
                    && (StatusConstans.PAGE.equals(paramName) || StatusConstans.ROWS.equals(paramName));
        }
    
        @Override
        public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                      NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
            String paramName = methodParameter.getParameterName();
            String paramValue = ((HttpServletRequest) nativeWebRequest.getNativeRequest()).getParameter(paramName);
    
            if (StatusConstans.ROWS.equals(paramName)) {
                try{
                    int rows = Integer.parseInt(paramValue);
                    return rows < 0 ? 10 : rows;
                }catch (NumberFormatException e){
                    log.error("解析row参数失败:" + paramValue);
                    return 10;
                }
            }
            if (StatusConstans.PAGE.equals(paramName)) {
                try{
                    int page = Integer.parseInt(paramValue);
                    return Math.max(page, 0);
                }catch (NumberFormatException e){
                    log.error("解析page参数失败:" + paramValue);
                    return 0;
                }
            }
            return null;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:SpringMVC分页参数自动注入

          本文链接:https://www.haomeiwen.com/subject/objloctx.html