I have created UrlRouter
. It should call appropriate controllers methods with extracted values as a parameters. It works fine, but my boss told me that I should make it better. Could you give me some advice on how to improve this class, please?
public class UrlRouter {
private final static String pageRegex = "/page/\\d{1,5}";
private final static String yearRegex = "/\\d{4}";
private final static String monthRegex = "/\\d{1,2}";
private final static String nameRegex = "/[a-z0-9\\-]+";
private final static Pattern page = Pattern.compile(pageRegex + "$");
private final static Pattern year = Pattern.compile(yearRegex + "$");
private final static Pattern yearPage = Pattern.compile(yearRegex + pageRegex + "$");
private final static Pattern yearMonth = Pattern.compile(yearRegex + monthRegex + "$");
private final static Pattern yearMonthPage = Pattern.compile(yearRegex + monthRegex + pageRegex + "$");
private final static Pattern yearMonthName = Pattern.compile(yearRegex + monthRegex + nameRegex + "$");
private PostController postController;
public UrlRouter(PostController controller) {
this.postController = controller;
}
public void route(HttpServletRequest request) {
String url = request.getRequestURI();
if (yearMonthName.matcher(url).find()) {
showOne(url);
} else if (yearMonthPage.matcher(url).find()) {
showMonthList(url);
} else if (yearMonth.matcher(url).find()) {
showMonth(url);
} else if (yearPage.matcher(url).find()) {
showYearList(url);
} else if (year.matcher(url).find()) {
showYear(url);
} else if (page.matcher(url).find()) {
showPage(url);
} else {
postController.showPage(1);
}
}
private void showPage(String url) {
String[] parts = url.split("/");
int pageNumber = Integer.parseInt(parts[parts.length-1]);
postController.showPage(pageNumber);
}
private void showYear(String url) {
String[] parts = url.split("/");
int year = Integer.parseInt(parts[parts.length - 1]);
postController.showYear(year, 1);
}
private void showYearList(String url) {
String[] parts = url.split("/");
int year = Integer.parseInt(parts[parts.length - 3]);
int page = Integer.parseInt(parts[parts.length - 1]);
postController.showYear(year, page);
}
private void showMonth(String url) {
String[] parts = url.split("/");
int month = Integer.parseInt(parts[parts.length - 1]);
int year = Integer.parseInt(parts[parts.length-2]);
postController.showMonth(year, month, 1);
}
private void showMonthList(String url) {
String[] parts = url.split("/");
int year = Integer.parseInt(parts[parts.length - 4]);
int month = Integer.parseInt(parts[parts.length - 3]);
int page = Integer.parseInt(parts[parts.length - 1]);
postController.showMonth(year, month, page);
}
private void showOne(String url) {
String[] parts = url.split("/");
int year = Integer.parseInt(parts[parts.length - 3]);
int month = Integer.parseInt(parts[parts.length - 2]);
String name = parts[parts.length - 1];
postController.showOne(year, month, name);
}
}