javax.servlet.ServletContext#getContextPath ( )源码实例Demo

下面列出了javax.servlet.ServletContext#getContextPath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lutece-core   文件: SpringContextService.java
/**
 * Returns a name for this context
 * 
 * @param servletContext the servlet context
 * @return name for this context
 */
private static String getContextName( ServletContext servletContext )
{
    String name = "lutece";

    if ( servletContext != null )
    {
        String contextName = servletContext.getServletContextName( );

        if ( contextName == null )
        {
            contextName = servletContext.getContextPath( );
        }

        if ( StringUtils.isNotBlank( contextName ) )
        {
            name = contextName;
        }
    }

    return name;
}
 
源代码2 项目: joynr   文件: TestRequestDispatcher.java
private void forwardToUrl(final String targetContextPath,
                          Request baseRequest,
                          HttpServletResponse response) throws ServletException, IOException {

    logger.info("Forward request {} to context {}", baseRequest.toString(), targetContextPath);

    synchronized (contextForwardCounts) {
        int currentContextForwardCount = 0;
        if (contextForwardCounts.containsKey(targetContextPath)) {
            currentContextForwardCount = contextForwardCounts.get(targetContextPath);
        }
        contextForwardCounts.put(targetContextPath, currentContextForwardCount + 1);
    }

    ServletContext currentContext = baseRequest.getServletContext();
    String currentContextPath = currentContext.getContextPath();

    String forwardContextPath = currentContextPath.replace(ClusteredBounceProxyWithDispatcher.CONTEXT_DISPATCHER,
                                                           targetContextPath);

    ServletContext forwardContext = currentContext.getContext(forwardContextPath);
    String forwardPath = baseRequest.getPathInfo();
    RequestDispatcher requestDispatcher = forwardContext.getRequestDispatcher(forwardPath);

    requestDispatcher.forward(baseRequest, response);
}
 
源代码3 项目: piranha   文件: TempDirInitializer.java
/**
 * On startup.
 *
 * @param classes the classes.
 * @param servletContext the servlet context.
 * @throws ServletException when a servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    File baseDir = new File("tmp");
    String name = servletContext.getContextPath();
    name = name.replaceAll("/", "_");
    if (name.trim().equals("")) {
        name = "ROOT";
    }
    File tempDir = new File(baseDir, name);
    if (!tempDir.exists()) {
        tempDir.mkdirs();
    }
    if (LOGGER.isLoggable(FINE)) {
        LOGGER.log(FINE, "Setting TEMPDIR for context ''{0}'' to ''{1}''",
                new Object[]{servletContext.getContextPath(), tempDir});
    }
    servletContext.setAttribute(TEMPDIR, tempDir);
}
 
源代码4 项目: o2oa   文件: Context.java
public static Context concrete(ServletContextEvent servletContextEvent) throws Exception {
	ServletContext servletContext = servletContextEvent.getServletContext();
	Context context = new Context();
	context.contextPath = servletContext.getContextPath();
	context.clazz = Class.forName(servletContext.getInitParameter(INITPARAMETER_PORJECT));
	context.module = context.clazz.getAnnotation(Module.class);
	context.name = context.module.name();
	context.path = servletContext.getRealPath("");
	context.servletContext = servletContext;
	context.servletContextName = servletContext.getServletContextName();
	context.clazz = Class.forName(servletContextEvent.getServletContext().getInitParameter(INITPARAMETER_PORJECT));
	context.initDatas();
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		// context.cleanupSchedule(emc);
		// context.cleanupScheduleLocal(emc);
		context.checkDefaultRole(emc);
	}
	servletContext.setAttribute(context.getClass().getName(), context);
	return context;
}
 
源代码5 项目: Tomcat8-Source-Read   文件: AuthenticatorBase.java
/**
 * Start this component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException
 *                if this component detects a fatal error that prevents this
 *                component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    ServletContext servletContext = context.getServletContext();
    jaspicAppContextID = servletContext.getVirtualServerName() + " " +
            servletContext.getContextPath();

    // Look up the SingleSignOn implementation in our request processing
    // path, if there is one
    Container parent = context.getParent();
    while ((sso == null) && (parent != null)) {
        Valve valves[] = parent.getPipeline().getValves();
        for (int i = 0; i < valves.length; i++) {
            if (valves[i] instanceof SingleSignOn) {
                sso = (SingleSignOn) valves[i];
                break;
            }
        }
        if (sso == null) {
            parent = parent.getParent();
        }
    }
    if (log.isDebugEnabled()) {
        if (sso != null) {
            log.debug("Found SingleSignOn Valve at " + sso);
        } else {
            log.debug("No SingleSignOn Valve is present");
        }
    }

    sessionIdGenerator = new StandardSessionIdGenerator();
    sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm());
    sessionIdGenerator.setSecureRandomClass(getSecureRandomClass());
    sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider());

    super.startInternal();
}
 
源代码6 项目: flow   文件: PwaConfiguration.java
protected PwaConfiguration(PWA pwa, ServletContext servletContext) {
    rootUrl = hasContextPath(servletContext)
            ? servletContext.getContextPath() + "/"
            : "/";
    if (pwa != null) {
        appName = pwa.name();
        shortName = pwa.shortName().substring(0,
                Math.min(pwa.shortName().length(), 12));
        description = pwa.description();
        backgroundColor = pwa.backgroundColor();
        themeColor = pwa.themeColor();
        iconPath = checkPath(pwa.iconPath());
        manifestPath = checkPath(pwa.manifestPath());
        offlinePath = checkPath(pwa.offlinePath());
        display = pwa.display();
        startPath = pwa.startPath().replaceAll("^/+", "");
        enabled = true;
        offlineResources = Arrays.asList(pwa.offlineResources());
    } else {
        appName = DEFAULT_NAME;
        shortName = "Flow PWA";
        description = "";
        backgroundColor = DEFAULT_BACKGROUND_COLOR;
        themeColor = DEFAULT_THEME_COLOR;
        iconPath = DEFAULT_ICON;
        manifestPath = DEFAULT_PATH;
        offlinePath = DEFAULT_OFFLINE_PATH;
        display = DEFAULT_DISPLAY;
        startPath = "";
        enabled = false;
        offlineResources = Collections.emptyList();
    }
}
 
/**
 * Parsing path
 */
private void decodePaths(){
    ServletContext servletContext = getServletContext();
    String contextPath = servletContext.getContextPath();
    boolean existContextPath = contextPath != null && contextPath.length() > 0;

    String sourceURI = forwardPath;
    if (sourceURI.indexOf('\\') > -1) {
        sourceURI = sourceURI.replace('\\', '/');
    }
    String servletPath = existContextPath? sourceURI.replace(contextPath, "") : sourceURI;
    if (servletPath.isEmpty() || servletPath.charAt(0)!= '/') {
        servletPath = '/' + servletPath;
    }

    //Parsing the queryString
    int queryInx = servletPath.indexOf('?');
    if (queryInx > -1) {
        this.queryString = servletPath.substring(queryInx + 1, servletPath.length());
        servletPath = servletPath.substring(0, queryInx);
    }

    //Parse the requestURI and ensure that the requestURI prefix is + /
    String requestURI;
    if(existContextPath){
        requestURI = '/' + contextPath + servletPath;
    }else {
        requestURI = servletPath;
    }

    this.servletPath = servletPath;
    this.requestURI = requestURI;
    // 1.Plus the pathInfo
    this.pathInfo = null;
    this.decodePathsFlag = true;
}
 
源代码8 项目: piranha   文件: AuthenticationInitializer.java
/**
 * Initialize Eleos
 * 
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    
    // Gets the authentication module class that was configured externally
    Class<?> authModuleClass = (Class<?>) servletContext.getAttribute(AUTH_MODULE_CLASS);
    if (authModuleClass == null) {
        authModuleClass = DoNothingServerAuthModule.class;
    }
    
    String appContextId = servletContext.getVirtualServerName() + " " + servletContext.getContextPath();
    
    // This sets the authentication factory to the default factory. This factory stores and retrieves
    // the authentication artifacts.
    Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, DefaultConfigFactory.class.getName());
    
    // Defines the modules that we have available. Here it's only a single fixed module.
    ConfigParser configParser = new DefaultConfigParser(authModuleClass);
    
    // Indicates the module we want to use
    Map<String, Object> options = new HashMap<>();
    options.put("authModuleId", authModuleClass.getSimpleName());
    
    // This authentication service installs an authentication config provider in the default factory, which
    // is the one we setup above. This authentication config provider uses the passed-in configParser to
    // retrieve configuration for authentication modules from.
    DefaultAuthenticationService authenticationService = new DefaultAuthenticationService(appContextId, options, configParser, null);
    
    servletContext.setAttribute(AUTH_SERVICE, authenticationService);
    
    servletContext.addFilter(AuthenticationFilter.class.getSimpleName(), AuthenticationFilter.class);
    
    // TMP - should use Dynamic
    ((WebApplication) servletContext).addFilterMapping(AuthenticationFilter.class.getSimpleName(), "/*");
}
 
源代码9 项目: lams   文件: CsrfGuardServletContextListener.java
@Override
public void contextInitialized(ServletContextEvent event) {
	ServletContext context = event.getServletContext();
	servletContext = context.getContextPath();
	//since this is just a prefix of a path, then if there is no servlet context, it is the empty string
	if (servletContext == null || "/".equals(servletContext)) {
		servletContext = "";
	}
	
	configFileName = context.getInitParameter(CONFIG_PARAM);

	if (configFileName == null) {
		configFileName = ConfigurationOverlayProvider.OWASP_CSRF_GUARD_PROPERTIES;
	}

	InputStream is = null;
	Properties properties = new Properties();

	try {
		is = getResourceStream(configFileName, context, false);
		
		if (is == null) {
			is = getResourceStream(ConfigurationOverlayProvider.META_INF_CSRFGUARD_PROPERTIES, context, false);
		}

		if (is == null) {
			throw new RuntimeException("Cant find default owasp csrfguard properties file: " + configFileName);
		}
		
		properties.load(is);
		CsrfGuard.load(properties);
	} catch (Exception e) {
		throw new RuntimeException(e);
	} finally {
		Streams.close(is);
	}


	printConfigIfConfigured(context, "Printing properties before Javascript servlet, note, the javascript properties might not be initialized yet: ");
}
 
源代码10 项目: dubbo-2.6.5   文件: RestProtocol.java
@Override
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = getAddr(url);
    Class implClass = ServiceClassHolder.getInstance().popServiceClass();
    RestServer server = servers.get(addr);
    if (server == null) {
        server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty"));
        server.start(url);
        servers.put(addr, server);
    }

    String contextPath = getContextPath(url);
    if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) {
        ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
        if (servletContext == null) {
            throw new RpcException("No servlet context found. Since you are using server='servlet', " +
                    "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
        }
        String webappPath = servletContext.getContextPath();
        if (StringUtils.isNotEmpty(webappPath)) {
            webappPath = webappPath.substring(1);
            if (!contextPath.startsWith(webappPath)) {
                throw new RpcException("Since you are using server='servlet', " +
                        "make sure that the 'contextpath' property starts with the path of external webapp");
            }
            contextPath = contextPath.substring(webappPath.length());
            if (contextPath.startsWith("/")) {
                contextPath = contextPath.substring(1);
            }
        }
    }

    final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;

    server.deploy(resourceDef, impl, contextPath);

    final RestServer s = server;
    return new Runnable() {
        @Override
        public void run() {
            // TODO due to dubbo's current architecture,
            // it will be called from registry protocol in the shutdown process and won't appear in logs
            s.undeploy(resourceDef);
        }
    };
}
 
源代码11 项目: pinpoint   文件: WebAppInterceptor.java
private String extractContextKey(ServletContext webapp) {
    String context = webapp.getContextPath();
    return StringUtils.isEmpty(context) ? "/ROOT" : context;
}
 
源代码12 项目: es   文件: IconController.java
/**
 * 如果量大 建议 在页面设置按钮 然后点击生成
 *
 * @param request
 * @return
 */
@RequestMapping(value = "/genCssFile")
@ResponseBody
public String genIconCssFile(HttpServletRequest request) {


    this.permissionList.assertHasEditPermission();


    String uploadFileTemplate = ".%1$s{background:url(%2$s/%3$s);width:%4$spx;height:%5$spx;display:inline-block;vertical-align: middle;%6$s}";
    String cssSpriteTemplate = ".%1$s{background:url(%2$s/%3$s) no-repeat -%4$spx -%5$spx;width:%6$spx;height:%7$spx;display:inline-block;vertical-align: middle;%8$s}";

    ServletContext sc = request.getServletContext();
    String ctx = sc.getContextPath();

    List<String> cssList = Lists.newArrayList();

    Searchable searchable = Searchable.newSearchable()
            .addSearchParam("type_in", new IconType[]{IconType.upload_file, IconType.css_sprite});

    List<Icon> iconList = baseService.findAllWithNoPageNoSort(searchable);

    for (Icon icon : iconList) {

        if (icon.getType() == IconType.upload_file) {
            cssList.add(String.format(
                    uploadFileTemplate,
                    icon.getIdentity(),
                    ctx, icon.getImgSrc(),
                    icon.getWidth(), icon.getHeight(),
                    icon.getStyle()));
            continue;
        }

        if (icon.getType() == IconType.css_sprite) {
            cssList.add(String.format(
                    cssSpriteTemplate,
                    icon.getIdentity(),
                    ctx, icon.getSpriteSrc(),
                    icon.getLeft(), icon.getTop(),
                    icon.getWidth(), icon.getHeight(),
                    icon.getStyle()));
            continue;
        }

    }

    try {
        ServletContextResource resource = new ServletContextResource(sc, iconClassFile);
        FileUtils.writeLines(resource.getFile(), cssList);
    } catch (Exception e) {
        LogUtils.logError("gen icon error", e);
        return "生成失败:" + e.getMessage();
    }

    return "生成成功";
}
 
源代码13 项目: dubbox   文件: RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = url.getIp() + ":" + url.getPort();
    Class implClass = ServiceClassHolder.getInstance().popServiceClass();
    RestServer server = servers.get(addr);
    if (server == null) {
        server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty"));
        server.start(url);
        servers.put(addr, server);
    }

    String contextPath = getContextPath(url);
    if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) {
        ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
        if (servletContext == null) {
            throw new RpcException("No servlet context found. Since you are using server='servlet', " +
                    "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
        }
        String webappPath = servletContext.getContextPath();
        if (StringUtils.isNotEmpty(webappPath)) {
            webappPath = webappPath.substring(1);
            if (!contextPath.startsWith(webappPath)) {
                throw new RpcException("Since you are using server='servlet', " +
                        "make sure that the 'contextpath' property starts with the path of external webapp");
            }
            contextPath = contextPath.substring(webappPath.length());
            if (contextPath.startsWith("/")) {
                contextPath = contextPath.substring(1);
            }
        }
    }

    final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;

    server.deploy(resourceDef, impl, contextPath);

    final RestServer s = server;
    return new Runnable() {
        public void run() {
            // TODO due to dubbo's current architecture,
            // it will be called from registry protocol in the shutdown process and won't appear in logs
            s.undeploy(resourceDef);
        }
    };
}
 
源代码14 项目: dubbox   文件: RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = url.getIp() + ":" + url.getPort();
    Class implClass = ServiceClassHolder.getInstance().popServiceClass();
    RestServer server = servers.get(addr);
    if (server == null) {
        server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty"));
        server.start(url);
        servers.put(addr, server);
    }

    String contextPath = getContextPath(url);
    if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) {
        ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
        if (servletContext == null) {
            throw new RpcException("No servlet context found. Since you are using server='servlet', " +
                    "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
        }
        String webappPath = servletContext.getContextPath();
        if (StringUtils.isNotEmpty(webappPath)) {
            webappPath = webappPath.substring(1);
            if (!contextPath.startsWith(webappPath)) {
                throw new RpcException("Since you are using server='servlet', " +
                        "make sure that the 'contextpath' property starts with the path of external webapp");
            }
            contextPath = contextPath.substring(webappPath.length());
            if (contextPath.startsWith("/")) {
                contextPath = contextPath.substring(1);
            }
        }
    }

    final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;

    server.deploy(resourceDef, impl, contextPath);

    final RestServer s = server;
    return new Runnable() {
        public void run() {
            // TODO due to dubbo's current architecture,
            // it will be called from registry protocol in the shutdown process and won't appear in logs
            s.undeploy(resourceDef);
        }
    };
}
 
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
  if(c == null || c.isEmpty()) {
    // skip deployments that do not carry a PA
    return;

  }

  if (c.contains(ProcessApplication.class)) {
    // this is a workaround for a bug in WebSphere-8.5 who
    // ships the annotation itself as part of the discovered classes.

    // copy into a fresh Set as we don't know if the original Set is mutable or immutable.
    c = new HashSet<Class<?>>(c);

    // and now remove the annotation itself.
    c.remove(ProcessApplication.class);
  }


  String contextPath = ctx.getContextPath();
  if(c.size() > 1) {
    // a deployment must only contain a single PA
    throw LOG.multiplePasException(c, contextPath);

  } else if(c.size() == 1) {
    Class<?> paClass = c.iterator().next();

    // validate whether it is a legal Process Application
    if(!AbstractProcessApplication.class.isAssignableFrom(paClass)) {
      throw LOG.paWrongTypeException(paClass);
    }

    // add it as listener if it's a ServletProcessApplication
    if(ServletProcessApplication.class.isAssignableFrom(paClass)) {
      LOG.detectedPa(paClass);
      ctx.addListener(paClass.getName());
    }
  }
  else {
    LOG.servletDeployerNoPaFound(contextPath);
  }

}
 
源代码16 项目: ICERest   文件: ICEREST.java
public boolean init(Config config, ServletContext servletContext) {
    this.servletContext = servletContext;
    this.contextPath = servletContext.getContextPath();
    iceIniter = new IceIniter(config, servletContext);
    return true;
}
 
源代码17 项目: flow   文件: PwaRegistry.java
private String initializeServiceWorker(ServletContext servletContext) {
    StringBuilder stringBuilder = new StringBuilder();

    // List of icons for precache
    List<String> filesToCahe = getIcons().stream()
            .filter(PwaIcon::shouldBeCached).map(PwaIcon::getCacheFormat)
            .collect(Collectors.toList());

    // Add offline page to precache
    filesToCahe.add(offlinePageCache());
    // Add manifest to precache
    filesToCahe.add(manifestCache());

    // Add user defined resources
    for (String resource : pwaConfiguration.getOfflineResources()) {
        filesToCahe.add(String.format(WORKBOX_CACHE_FORMAT,
                resource.replaceAll("'", ""), servletContext.hashCode()));
    }

    String workBoxAbsolutePath = servletContext.getContextPath() + "/"
            + WORKBOX_FOLDER;
    // Google Workbox import
    stringBuilder.append("importScripts('").append(workBoxAbsolutePath)
            .append("workbox-sw.js").append("');\n\n");

    stringBuilder.append("workbox.setConfig({\n")
            .append("  modulePathPrefix: '").append(workBoxAbsolutePath)
            .append("'\n").append("});\n");

    // Precaching
    stringBuilder.append("workbox.precaching.precacheAndRoute([\n");
    stringBuilder.append(String.join(",\n", filesToCahe));
    stringBuilder.append("\n]);\n");

    // Offline fallback
    stringBuilder
            .append("self.addEventListener('fetch', function(event) {\n")
            .append("  var request = event.request;\n")
            .append("  if (request.mode === 'navigate') {\n")
            .append("    event.respondWith(\n      fetch(request)\n")
            .append("        .catch(function() {\n")
            .append(String.format("          return caches.match('%s');%n",
                    getPwaConfiguration().getOfflinePath()))
            .append("        })\n    );\n  }\n });");

    return stringBuilder.toString();
}
 
源代码18 项目: dubbox   文件: RestProtocol.java
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = url.getIp() + ":" + url.getPort();
    Class implClass = ServiceClassHolder.getInstance().popServiceClass();
    RestServer server = servers.get(addr);
    if (server == null) {
        server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty"));
        server.start(url);
        servers.put(addr, server);
    }

    String contextPath = getContextPath(url);
    if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) {
        ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
        if (servletContext == null) {
            throw new RpcException("No servlet context found. Since you are using server='servlet', " +
                    "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
        }
        String webappPath = servletContext.getContextPath();
        if (StringUtils.isNotEmpty(webappPath)) {
            webappPath = webappPath.substring(1);
            if (!contextPath.startsWith(webappPath)) {
                throw new RpcException("Since you are using server='servlet', " +
                        "make sure that the 'contextpath' property starts with the path of external webapp");
            }
            contextPath = contextPath.substring(webappPath.length());
            if (contextPath.startsWith("/")) {
                contextPath = contextPath.substring(1);
            }
        }
    }

    final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;

    server.deploy(resourceDef, impl, contextPath);

    final RestServer s = server;
    return new Runnable() {
        public void run() {
            // TODO due to dubbo's current architecture,
            // it will be called from registry protocol in the shutdown process and won't appear in logs
            s.undeploy(resourceDef);
        }
    };
}
 
源代码19 项目: eplmp   文件: CustomServletContextListener.java
public static String getAppContextID(ServletContext context) {
    return context.getVirtualServerName() + " " + context.getContextPath();
}
 
源代码20 项目: flow   文件: PwaConfiguration.java
private static boolean hasContextPath(ServletContext servletContext) {
    return !(servletContext == null
            || servletContext.getContextPath() == null
            || servletContext.getContextPath().isEmpty());
}