SpringMVC分页参数自动注入

通过实现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分页参数自动注入)