경로 길이를 조정하는 부분은
begin,end,lastIndexOf("/")이 세 가지가 핵심이다.
URI 시작점 계산
String contextPath = request.getContextPath();
String uri = (String)request.getAttribute("javax.servlet.include.request_uri");
int i = 1;
if(uri == null || uri.trim().equals("")) {
uri = request.getRequestURI();
}
int begin = 0;
if(!(contextPath == null) || !("".equals(contextPath))) {
begin = contextPath.length();
}
int end = 0;
if(uri.indexOf(";") != -1) {
end = uri.indexOf(";");
}else if(uri.indexOf("?") != -1) {
end = uri.indexOf("?");
}else {
end = uri.length();
}
String viewName = uri.substring(begin, end);
System.out.println(i++ + " : " + viewName);
if(viewName.lastIndexOf(".") != -1) {
viewName = viewName.substring(0, viewName.lastIndexOf("."));
}
System.out.println(i++ + " : " + viewName);
if(viewName.lastIndexOf("/") != -1) {
viewName = viewName.substring(viewName.lastIndexOf("/", 1), viewName.length());
}
System.out.println(i++ + " : " + viewName);
return viewName;
}
String contextPath = request.getContextPath();
String uri = (String)request.getAttribute("javax.servlet.include.request_uri");
contextPath 는 웹 애플리케이션의 루트 경로를 말한다. (/pro10 같은 값)
javax.servlet.include.request_uri 속성을 가져오는데, 이 속성은 포워드(forward)된 경우 원래 요청 URI를 포함한다.
만약 uri가 null이면 request.getRequestURI()를 사용해서 현재 요청된 URI를 가져온다.
int begin = 0;
if(!(contextPath == null) || !("".equals(contextPath))) {
begin = contextPath.length();
}
contextPath 가 존재하면, 그 길이를 URI의 시작 인덱스로 한다.예: contextPath = "/pro10" , uri = "/pro10/member/info.jsp" → begin = 6
/pro10 을 제외한 /member/info.jsp 만 남는다.int end = 0;
if(uri.indexOf(";") != -1) {
end = uri.indexOf(";");
} else if(uri.indexOf("?") != -1) {
end = uri.indexOf("?");
} else {
end = uri.length();
}
; 또는 ? 는 세션 ID 또는 쿼리 스트링이 포함될 때 사용된다.예: /pro10/member/info.jsp;jsessionid=1234
예: /pro10/member/info.jsp?user=admin
세미콜론 ;이 있으면 그 앞까지 자른다.
물음표 ?가 있으면 그 앞까지 자른다.
없으면 URI 전체를 사용한다.
String viewName = uri.substring(begin, end);
contextPath 다음부터 ; 또는 ? 이전까지 남는다.예: uri = "/pro10/member/info.jsp" → viewName = "/member/info.jsp"
if(viewName.lastIndexOf(".") != -1) {
viewName = viewName.substring(0, viewName.lastIndexOf("."));
}
.jsp 같은 파일 확장자를 제거한다.예: viewName = "/member/info.jsp" → "viewName = "/member/info"
if(viewName.lastIndexOf("/") != -1) {
viewName = viewName.substring(viewName.lastIndexOf("/", 1), viewName.length());
}
lastIndexOf("/") 를 이용해 마지막 / 뒤에 있는 문자열만 남긴다.예: viewName = "/member/info" → 최종적으로 `"info" 만 남는다.