[SPRING] MVC에서 동적 뷰 매핑

수경·2025년 3월 25일

SpringFrameWork

목록 보기
13/24
post-thumbnail

URI에서 뷰 이름 추출

경로 길이를 조정하는 부분은 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;
	}

1. contextPath를 기준으로 URI의 시작점 계산

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를 가져온다.

2. contextPath 길이를 이용하여 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 만 남는다.

3. URI에서 ';', '?'가 있으면 그 앞까지만 사용

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 전체를 사용한다.

4. contextPath 이후 부분만 가져오기

String viewName = uri.substring(begin, end);
  • contextPath 다음부터 ; 또는 ? 이전까지 남는다.

예: uri = "/pro10/member/info.jsp"viewName = "/member/info.jsp"

5. 파일 확장자 제거 (.jsp 등)

if(viewName.lastIndexOf(".") != -1) {
    viewName = viewName.substring(0, viewName.lastIndexOf("."));
}
  • .jsp 같은 파일 확장자를 제거한다.

예: viewName = "/member/info.jsp""viewName = "/member/info"

6. 마지막 '/' 이후의 문자열만 남기기 (즉, 최종 뷰 이름 추출)

if(viewName.lastIndexOf("/") != -1) {
    viewName = viewName.substring(viewName.lastIndexOf("/", 1), viewName.length());
}
  • lastIndexOf("/") 를 이용해 마지막 / 뒤에 있는 문자열만 남긴다.

예: viewName = "/member/info" → 최종적으로 `"info" 만 남는다.

profile
개발 공부중•••

0개의 댓글