Pages

Tuesday, January 13, 2015

Accessing Context Root Programatically


There are several needs to access context root in various places of your application.

Various ways are,

In Jspx${pageContext.request.contextPath}

In servlet:
    public static String getContextpath(HttpServletRequest request) {
        return request != null ? request.getContextPath() : null;
    }

In bean:
   public static String getContextpath() {
        ExternalContext extContext= FacesContext.getCurrentInstance().getExternalContext();
        String url = extContext.getRequestContextPath();
        return url;
    }

In Javascript:
function getContextPath(){
            return window.location.pathname.substring(0,window.location.pathname.indexOf("/",2));
            }

In CSSbackground: url(../resources/images/header.jpg")