com.jslsolucoes.spring.paginate.Paginator Maven / Gradle / Ivy
package com.jslsolucoes.spring.paginate;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class Paginator {
private Integer maxResults;
private Integer firstResult;
private HttpServletRequest httpServletRequest;
private static final Logger logger = LoggerFactory.getLogger(Paginator.class);
public Paginator() {
}
@Autowired
public Paginator(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
@PostConstruct
public void calculate() {
this.maxResults = maxResults();
this.firstResult = firstResult();
logger.debug("Calculating pagination first result:{}, max results:{}", firstResult, maxResults);
}
private Integer firstResult() {
return (page() * this.maxResults) - this.maxResults;
}
private Integer page() {
return parameterFor("page", 1);
}
private Integer maxResults() {
return parameterFor("resultsPerPage", 60);
}
private Integer parameterFor(String parameterName, Integer defaultValue) {
String parameter = httpServletRequest.getParameter(parameterName);
if (parameter == null) {
return defaultValue;
} else {
return Integer.valueOf(parameter);
}
}
public Integer getMaxResults() {
return maxResults;
}
public Integer getFirstResult() {
return firstResult;
}
}