HandlerMethodResolver

배세훈·2021년 6월 9일
0

Spring

목록 보기
2/38

HandlerMethodResolver 구현

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static org.apache.commons.lang3.math.NumberUtils.toInt;
import static org.apache.commons.lang3.math.NumberUtils.toLong;

public class PageMethodArgumentResolver implements HandlerMethodArgumentResolver {

  private static final int DEFAULT_OFFSET = 0;

  private static final int DEFAULT_LIMIT = 15;

  private final String offset;

  private final String limit;

  public PageMethodArgumentResolver() {
    this("offset", "limit");
  }

  public PageMethodArgumentResolver(String offset, String limit) {
    this.offset = offset;
    this.limit = limit;
  }

  @Override
  public boolean supportsParameter(MethodParameter parameter) {
  	// Page라는 클래스이거나 Page를 상속받은 모든 클래스 타입인지 확인하여 true인 경우 아래의 resolverArgument 실행
    return Page.class.isAssignableFrom(parameter.getParameterType());
  }

  @Override
  public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
    String offsetString = webRequest.getParameter(offset);
    String limitString = webRequest.getParameter(limit);

    long offset = toLong(offsetString, DEFAULT_OFFSET);
    int limit = toInt(limitString, DEFAULT_LIMIT);

    if (offset < 0) {
      offset = DEFAULT_OFFSET;
    }
    if (limit < 1 || limit > 5) {
      limit = DEFAULT_LIMIT;
    }

    return new Page(offset, limit);
  }
}
profile
성장형 인간

0개의 댓글