javax.servlet.ServletContext.getRealPath()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(217)

本文整理了Java中javax.servlet.ServletContext.getRealPath()方法的一些代码示例,展示了ServletContext.getRealPath()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ServletContext.getRealPath()方法的具体详情如下:
包路径:javax.servlet.ServletContext
类名称:ServletContext
方法名:getRealPath

ServletContext.getRealPath介绍

[英]Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..

The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).
[中]返回一个String,其中包含给定虚拟路径的实际路径。例如,路径“/index.html”返回服务器文件系统上的绝对文件路径,请求http://host/contextPath/index.html,其中contextPath是此ServletContext的上下文路径。。
返回的实际路径将采用适合于运行servlet容器的计算机和操作系统的形式,包括正确的路径分隔符。如果servlet容器由于任何原因(例如,当内容从.war存档中可用时)无法将虚拟路径转换为真实路径,则此方法返回null

代码示例

代码示例来源:origin: stackoverflow.com

@Autowired
ServletContext servletContext;

... myMethod() { 
   File rootDir = new File( servletContext.getRealPath("/WEB-INF/myDIR/") );
}

代码示例来源:origin: gocd/gocd

Map loadManifest() throws IOException {
  File manifestFile = new File(servletContext.getRealPath(servletContext.getInitParameter("rails.root") + "/public/assets/webpack/manifest.json"));
  if (!manifestFile.exists()) {
    throw new RuntimeException("Could not load compiled manifest from 'webpack/manifest.json' - have you run `rake webpack:compile`?");
  }
  Gson gson = new Gson();
  Map manifest = gson.fromJson(FileUtils.readFileToString(manifestFile, UTF_8), Map.class);
  if (manifest.containsKey("errors") && !((List) manifest.get("errors")).isEmpty()) {
    throw new RuntimeException("There were errors in manifest.json file");
  }
  Map entrypoints = (Map) manifest.get("entrypoints");
  if (entrypoints == null) {
    throw new RuntimeException("Could not find any entrypoints in the manifest.json file.");
  }
  return entrypoints;
}

代码示例来源:origin: ronmamo/reflections

/**
 * Returns the URL of the {@code WEB-INF/classes} folder.
 * <p>
 * This finds the URLs using the {@link ServletContext}.
 * 
 * @return the collection of URLs, not null
 */
public static URL forWebInfClasses(final ServletContext servletContext) {
  try {
    final String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path != null) {
      final File file = new File(path);
      if (file.exists())
        return file.toURL();
    } else {
      return servletContext.getResource("/WEB-INF/classes");
    }
  } catch (MalformedURLException e) { /*fuck off*/ }
  return null;
}

代码示例来源:origin: org.reflections/reflections

/**
 * Returns the URL of the {@code WEB-INF/classes} folder.
 * <p>
 * This finds the URLs using the {@link ServletContext}.
 * 
 * @return the collection of URLs, not null
 */
public static URL forWebInfClasses(final ServletContext servletContext) {
  try {
    final String path = servletContext.getRealPath("/WEB-INF/classes");
    if (path != null) {
      final File file = new File(path);
      if (file.exists())
        return file.toURL();
    } else {
      return servletContext.getResource("/WEB-INF/classes");
    }
  } catch (MalformedURLException e) { /*fuck off*/ }
  return null;
}

代码示例来源:origin: gocd/gocd

public void initialize() throws IOException {
  if (!systemEnvironment.useCompressedJs()) {
    return;
  }
  String assetsDirPath = servletContext.getRealPath(servletContext.getInitParameter("rails.root") + "/public/assets/");
  File assetsDir = new File(assetsDirPath);
  if (!assetsDir.exists()) {
    throw new RuntimeException(String.format("Assets directory does not exist %s", assetsDirPath));
  }
  Collection files = FileUtils.listFiles(assetsDir, new RegexFileFilter(MANIFEST_FILE_PATTERN), null);
  if (files.isEmpty()) {
    throw new RuntimeException(String.format("Manifest json file was not found at %s", assetsDirPath));
  }
  File manifestFile = (File) files.iterator().next();
  LOG.info("Found rails assets manifest file named {} ", manifestFile.getName());
  String manifest = FileUtils.readFileToString(manifestFile, UTF_8);
  Gson gson = new Gson();
  railsAssetsManifest = gson.fromJson(manifest, RailsAssetsManifest.class);
  LOG.info("Successfully read rails assets manifest file located at {}", manifestFile.getAbsolutePath());
}

代码示例来源:origin: apache/hive

@Override
 protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
  throws ServletException, IOException {
  String absoluteDiskPath = getServletContext().getRealPath(req.getPathInfo());
  File requestedFile = new File(absoluteDiskPath);
  // async-profiler version 1.4 writes 'Started [cpu] profiling' to output file when profiler is running which
  // gets replaced by final output. If final output is not ready yet, the file size will be <100 bytes (in all modes).
  if (requestedFile.length() < 100) {
   LOG.info("{} is incomplete. Sending auto-refresh header..", requestedFile);
   resp.setHeader("Refresh", "2," + req.getRequestURI());
   resp.getWriter().write("This page will auto-refresh every 2 second until output file is ready..");
  } else {
   super.doGet(req, resp);
  }
 }
}

代码示例来源:origin: nutzam/nutz

public String getAppRoot() {
  String webinf = getServletContext().getRealPath("/WEB-INF/");
  if (webinf == null) {
    log.info("/WEB-INF/ not Found?!");
    if (new File("src/main/webapp").exists())
      return new File("src/main/webapp").getAbsolutePath();
    if (new File("src/main/resources/webapp").exists())
      return new File("src/main/resources/webapp").getAbsolutePath();
    return "./webapp";
  }
  String root = getServletContext().getRealPath("/").replace('\\', '/');
  if (root.endsWith("/"))
    return root.substring(0, root.length() - 1);
  else if (root.endsWith("/."))
    return root.substring(0, root.length() - 2);
  return root;
}

代码示例来源:origin: groovy/groovy-core

/**
 * Parses the http request for the real script or template source file.
 * 
 * @param request
 *            the http request to analyze
 * @return a file object using an absolute file path name, or <code>null</code> if the
 *         servlet container cannot translate the virtual path to a real
 *         path for any reason (such as when the content is being made
 *         available from a .war archive).
 */
protected File getScriptUriAsFile(HttpServletRequest request) {
  String uri = getScriptUri(request);
  String real = servletContext.getRealPath(uri);
  if (real == null) {
    return null;
  }
  return new File(real).getAbsoluteFile();
}

代码示例来源:origin: stackoverflow.com

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

   ServletContext cntx= req.getServletContext();
   // Get the absolute path of the image
   String filename = cntx.getRealPath("Images/button.png");
   // retrieve mimeType dynamically
   String mime = cntx.getMimeType(filename);
   if (mime == null) {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return;
   }

   resp.setContentType(mime);
   File file = new File(filename);
   resp.setContentLength((int)file.length());

   FileInputStream in = new FileInputStream(file);
   OutputStream out = resp.getOutputStream();

   // Copy the contents of the file to the output stream
    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
     out.write(buf, 0, count);
   }
  out.close();
  in.close();

}

代码示例来源:origin: groovy/groovy-core

protected void generateNamePrefixOnce () {
  URI uri = null;
  String realPath = servletContext.getRealPath("/");
  if (realPath != null) { uri = new File(realPath).toURI();}//prevent NPE if in .war
  try {
    URL res = servletContext.getResource("/");
    if (res != null) { uri = res.toURI(); }
  } catch (MalformedURLException ignore) {
  } catch (URISyntaxException ignore) {
  }
  if (uri != null) {
    try {
      namePrefix = uri.toURL().toExternalForm();
      return;
    } catch (MalformedURLException e) {
      log("generateNamePrefixOnce [ERROR] Malformed URL for base path / == '"+ uri +'\'', e);
    }
  }
  namePrefix = "";
}

代码示例来源:origin: jenkinsci/jenkins

String value = (String) env.lookup(name);
    if(value!=null && value.trim().length()>0)
      return new FileAndDescription(new File(value.trim()),"JNDI/java:comp/env/"+name);
      return new FileAndDescription(new File(value.trim()),"JNDI/"+name);
  } catch (NamingException e) {
String root = event.getServletContext().getRealPath("/WEB-INF/workspace");
if(root!=null) {
  File ws = new File(root.trim());

代码示例来源:origin: geoserver/geoserver

String filepath = servletContext.getRealPath(path);
if (filepath != null) {
  File file = new File(filepath);
  if (file.exists()) {
    return file;
  if (index < items.size()) {
    filepath = servletContext.getRealPath(items.get(index));
    index++;
    if (filepath != null) {
      File file = new File(filepath);
      while (index < items.size()) {
        file = new File(file, items.get(index));
        index++;

代码示例来源:origin: stanfordnlp/CoreNLP

spacing = "true".equals(spacingStr);
String path = getServletContext().getRealPath("/WEB-INF/data/models");
for (String classifier : new File(path).list()) {
 classifiers.add(classifier);

代码示例来源:origin: stanfordnlp/CoreNLP

@Override
public void init() throws ServletException {
 pipeline = new StanfordCoreNLP();
 String xslPath = getServletContext().
           getRealPath("/WEB-INF/data/CoreNLP-to-HTML.xsl");
 try {
  Builder builder = new Builder();
  Document stylesheet = builder.build(new File(xslPath));
  corenlpTransformer = new XSLTransform(stylesheet);
 } catch (Exception e) {
  throw new ServletException(e);
 }
}

代码示例来源:origin: Red5/red5-server

String prefix = servletContext.getRealPath("/");
  File webapps = new File(prefix);
  System.setProperty("red5.webapp.root", webapps.getParent());
  webapps = null;

代码示例来源:origin: geoserver/geoserver

File fh = new File(value);
dataDirStr = servContext.getRealPath("/data");
LOGGER.info("Falling back to embedded data directory: " + dataDirStr);

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

String gzipPath = path + ".gz";
if (useGzipCompression(request, response, path, gzipPath)) {
  File output = new File(getServletContext().getRealPath(gzipPath));
  if (output.exists()) {
    response.addHeader("Content-Encoding", "gzip");

代码示例来源:origin: org.freemarker/freemarker

public Object findTemplateSource(String name) throws IOException {
  String fullPath = subdirPath + name;
  if (attemptFileAccess) {
    // First try to open as plain file (to bypass servlet container resource caches).
    try {
      String realPath = servletContext.getRealPath(fullPath);
      if (realPath != null) {
        File file = new File(realPath);
        if (file.canRead() && file.isFile()) {
          return file;
        }
      }
    } catch (SecurityException e) {
      ;// ignore
    }
  }
  // If it fails, try to open it with servletContext.getResource.
  URL url = null;
  try {
    url = servletContext.getResource(fullPath);
  } catch (MalformedURLException e) {
    LOG.warn("Could not retrieve resource " + StringUtil.jQuoteNoXSS(fullPath),
        e);
    return null;
  }
  return url == null ? null : new URLTemplateSource(url, getURLConnectionUsesCaches());
}

代码示例来源:origin: stanfordnlp/CoreNLP

if(testPropertiesFile != null && new File(testPropertiesFile).exists()){
 try {
  String props = IOUtils.stringFromFile(testPropertiesFile);
String modelDir = getServletContext().getRealPath("/WEB-INF/data/"+modelNametoDirName.get(model));
testProps.setProperty("patternsWordsDir", modelDir);
logger.info("Reading saved model from " + modelDir);

代码示例来源:origin: Atmosphere/atmosphere

private void scanForCustomAnnotation(Set<Class<?>> atmosphereAnnotatedClasses) throws IOException {
  handler.flushCoreAnnotations(atmosphereAnnotatedClasses);
  BytecodeBasedAnnotationProcessor b = new BytecodeBasedAnnotationProcessor(handler);
  b.configure(framework.getAtmosphereConfig());
  String path = framework.getServletContext().getRealPath(framework.getHandlersPath());
  if (path != null) {
    b.scan(new File(path)).destroy();
  } else {
    logger.warn("Unable to scan using File. Scanning classpath");
    b.scanAll();
  }
}

相关文章

微信公众号

最新文章

更多

ServletContext类方法