http://localhost:8080/contextpath/servletpath/main.do
다음과 같이 main.do를 진행했을 때
public class ViewNameInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String viewName = getViewName(request);
        request.setAttribute("viewName", viewName);
        return true;
    }

    private String getViewName(HttpServletRequest request) throws Exception{
        // contextPath 변수에 request.getContextPaht()로 /contextpath 경로를 얻어온다
        String contextPath = request.getContextPath();
        
        // uri 변수에는 javax.servlet.include.request_uri로 포트번호와 쿼리 사이에 경로를 가져온다.
        // /contextPath/servletPath/main.do
        String uri = (String) request.getAttribute("javax.servlet.include.request_uri");
        
        //만약 uri가 include된 jsp 파일이 아닐 경우 에는 아래와 같이
        //null과 uri.trim().equals("")로 좌우 여백 제거 및 공백인지 체크 후 getRequestURI로
        // /contextPath/servletPath/main.do 포트번호와 쿼리 사이에 경로를 가져온다.
        if(uri == null || uri.trim().equals("")){
            uri = request.getRequestURI();
        }

        int begin = 0;
        
        // contextPath가 null 또는 공백이 아닐 경우 begin에 contextPath의 길이를 저장
        if (!((contextPath == null) || ("".equals(contextPath)))){
            begin = contextPath.length();
        }
        int end;
        
        // uri의 indexOf로 ;가 들어간 인덱스가 -1이 아닐 때 ;의 인덱스 번호를 end에 저장한다.
        if(uri.indexOf(";") != -1){
        	end = uri.indexOf(";");
        } else if (uri.indexOf("?") != -1) {
        	// 위와 동일한데 ?가 -1이 아닐 때 저장한다.
            end = uri.indexOf("?");
        } else {
        	// 둘다 해당되지 않을 때는 uri의 길이를 저장한다
        	end = uri.length();
        }
        String fileName = uri.substring(begin, end);
        if(fileName.indexOf(".") != -1){
        	fileName = fileName.substring(0, fileName.lastIndexOf("."));
        }
        if(fileName.lastIndexOf("/")!= -1){
        	fileName = fileName.substring(fileName.lastIndexOf("/",1),fileName.length());
        }
        return fileName;
    }

}

+ Recent posts