当前位置: 首页>>代码示例>>Java>>正文


Java ServletContext.getRealPath方法代码示例

本文整理汇总了Java中javax.servlet.ServletContext.getRealPath方法的典型用法代码示例。如果您正苦于以下问题:Java ServletContext.getRealPath方法的具体用法?Java ServletContext.getRealPath怎么用?Java ServletContext.getRealPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.servlet.ServletContext的用法示例。


在下文中一共展示了ServletContext.getRealPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: upload

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 *
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping("/upload")
public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
    ServletContext sc = request.getSession().getServletContext();
    String dir = sc.getRealPath("/upload");
    String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    String imgName = "";
    if (type.equals("jpg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
    } else if (type.equals("png")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
    } else if (type.equals("jpeg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
    } else {
        return null;
    }
    FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
    response.getWriter().print("upload/" + imgName);
    return null;
}
 
开发者ID:ZHENFENG13,项目名称:ssm-demo,代码行数:30,代码来源:LoadImageController.java

示例2: upload

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public Result upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
    ServletContext sc = request.getSession().getServletContext();
    String dir = sc.getRealPath("/upload");
    String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    String imgName = "";
    if (type.equals("jpg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
    } else if (type.equals("png")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
    } else if (type.equals("jpeg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
    } else {
        return null;
    }
    FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
    Result result = ResultGenerator.genSuccessResult();
    result.setData("upload/" + imgName);
    return result;
}
 
开发者ID:ZHENFENG13,项目名称:perfect-ssm,代码行数:30,代码来源:LoadImageController.java

示例3: getRealPath

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * Return the real path of the specified virtual path.
 *
 * @param path Path to be translated
 *
 * @deprecated As of version 2.1 of the Java Servlet API, use
 *  <code>ServletContext.getRealPath()</code>.
 */
public String getRealPath(String path) {

    if (context == null)
        return (null);
    ServletContext servletContext = context.getServletContext();
    if (servletContext == null)
        return (null);
    else {
        try {
            return (servletContext.getRealPath(path));
        } catch (IllegalArgumentException e) {
            return (null);
        }
    }

}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:Request.java

示例4: setServletContext

import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public void setServletContext(ServletContext servletContext) {
    _log.info("===== 开始解压lambo-admin =====");
    String version = PropertiesFileUtil.getInstance("lambo-admin-client").get("lambo.admin.version");
    _log.info("lambo-admin.jar 版本: {}", version);
    String jarPath = servletContext.getRealPath("/WEB-INF/lib/lambo-admin-" + version + ".jar");
    _log.info("lambo-admin.jar 包路径: {}", jarPath);
    String resources = servletContext.getRealPath("/") + "/resources/lambo-admin";
    _log.info("lambo-admin.jar 解压到: {}", resources);
    JarUtil.decompress(jarPath, resources);
    _log.info("===== 解压lambo-admin完成 =====");
}
 
开发者ID:sunzhen086,项目名称:lambo,代码行数:13,代码来源:LamboAdminUtil.java

示例5: setWebAppRootSystemProperty

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substition with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
			"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException(
			"Web app root system property already set to different value: '" +
			key + "' = [" + oldValue + "] instead of [" + root + "] - " +
			"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:34,代码来源:WebUtils.java

示例6: setServletContext

import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public void setServletContext(ServletContext servletContext) {
    _log.info("===== 开始解压zheng-admin =====");
    String version = PropertiesFileUtil.getInstance("zheng-admin-client").get("zheng.admin.version");
    _log.info("zheng-admin.jar 版本: {}", version);
    String jarPath = servletContext.getRealPath("/WEB-INF/lib/zheng-admin-" + version + ".jar");
    _log.info("zheng-admin.jar 包路径: {}", jarPath);
    String resources = servletContext.getRealPath("/") + "/resources/zheng-admin";
    _log.info("zheng-admin.jar 解压到: {}", resources);
    JarUtil.decompress(jarPath, resources);
    _log.info("===== 解压zheng-admin完成 =====");
}
 
开发者ID:javay,项目名称:zheng-lite,代码行数:13,代码来源:ZhengAdminUtil.java

示例7: buildClassPath

import javax.servlet.ServletContext; //导入方法依赖的package包/类
private boolean buildClassPath(ServletContext servletContext,
        StringBuilder classpath, ClassLoader loader) {
    if (loader instanceof URLClassLoader) {
        URL repositories[] =
                ((URLClassLoader) loader).getURLs();
            for (int i = 0; i < repositories.length; i++) {
                String repository = repositories[i].toString();
                if (repository.startsWith("file://"))
                    repository = utf8Decode(repository.substring(7));
                else if (repository.startsWith("file:"))
                    repository = utf8Decode(repository.substring(5));
                else if (repository.startsWith("jndi:"))
                    repository =
                        servletContext.getRealPath(repository.substring(5));
                else
                    continue;
                if (repository == null)
                    continue;
                if (classpath.length() > 0)
                    classpath.append(File.pathSeparator);
                classpath.append(repository);
            }
    } else {
        String cp = getClasspath(loader);
        if (cp == null) {
            log.info( "Unknown loader " + loader + " " + loader.getClass());
        } else {
            if (classpath.length() > 0)
                classpath.append(File.pathSeparator);
            classpath.append(cp);
        }
        return false;
    }
    return true;
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:36,代码来源:WebappLoader.java

示例8: crateHTML

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * 生成静态页面主方法
 * 
 * @param context
 *            ServletContext
 * @param data
 *            一个Map的数据结果集
 * @param templatePath
 *            ftl模版路径
 * @param targetHtmlPath
 *            生成静态页面的路径
 */
public static void crateHTML(ServletContext context, Object data, String templatePath, String targetHtmlPath) {
    Configuration freemarkerCfg = new Configuration();
    // 加载模版
    freemarkerCfg.setServletContextForTemplateLoading(context, "/");
    freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
    try {
        // 指定模版路径
        Template template = freemarkerCfg.getTemplate(templatePath, "UTF-8");
        template.setEncoding("UTF-8");
        // 静态页面路径
        String htmlPathString = context.getRealPath("/") + "/" + targetHtmlPath;
        File htmlFile = new File(htmlPathString);

        if (!htmlFile.getParentFile().exists()) {
            htmlFile.getParentFile().mkdirs();
        }
        htmlFile.createNewFile();
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
        // 处理模版
        template.process(data, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        logger.error("error occured where generate Html file.", e);
    }
}
 
开发者ID:luckyyeah,项目名称:YiDu-Novel,代码行数:39,代码来源:StaticUtils.java

示例9: buildSurveyHtml

import javax.servlet.ServletContext; //导入方法依赖的package包/类
private void buildSurveyHtml() throws Exception{
		HttpServletRequest request=Struts2Utils.getRequest();
		HttpServletResponse response=Struts2Utils.getResponse();
		String url = "";
		String name = "";
		ServletContext sc = ServletActionContext.getServletContext();

		String file_name = request.getParameter("file_name");
		url = "/design/my-collect.action?surveyId=402880ea4675ac62014675ac7b3a0000";
		// 这是生成的html文件名,如index.htm.
		name = "/survey.htm";
		name = sc.getRealPath(name);
		
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		final ByteArrayOutputStream os = new ByteArrayOutputStream();

		final ServletOutputStream stream = new ServletOutputStream() {
			public void write(byte[] data, int offset, int length) {
				os.write(data, offset, length);
			}

			public void write(int b) throws IOException {
				os.write(b);
			}
		};
		
		final PrintWriter pw = new PrintWriter(new OutputStreamWriter(os,"utf-8"));

		HttpServletResponse rep = new HttpServletResponseWrapper(response) {
			public ServletOutputStream getOutputStream() {
				return stream;
			}

			public PrintWriter getWriter() {
				return pw;
			}
		};

//		rd.include(request, rep);
		rd.forward(request,rep);
		pw.flush();
		
		// 把jsp输出的内容写到xxx.htm
		File file = new File(name);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		
		os.writeTo(fos);
		fos.close();
	}
 
开发者ID:wkeyuan,项目名称:DWSurvey,代码行数:53,代码来源:MySurveyDesignAction.java

示例10: getBasePath

import javax.servlet.ServletContext; //导入方法依赖的package包/类
private void getBasePath(InterceptContext context, ServletContext sContext) {

        String basePath = sContext.getRealPath("");

        if (basePath.lastIndexOf("/") == (basePath.length() - 1)
                || basePath.lastIndexOf("\\") == (basePath.length() - 1)) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }

        context.put(InterceptConstants.BASEPATH, basePath);
    }
 
开发者ID:uavorg,项目名称:uavstack,代码行数:12,代码来源:TomcatPlusIT.java

示例11: contextInitialized

import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public void contextInitialized( ServletContextEvent servletEvent ) {

    ServletContext servletContext = servletEvent.getServletContext();
    servletContext.log("Servlet context initialized event is received. Starting registering configurators");
    try {
        new ClasspathUtils().logProblematicJars();
    } catch (RuntimeException e) {
        log.warn("Error caught while trying to get all JARs in classpath", e);
        // do not rethrow exception as this will stop deployment on incompliant servers like JBoss
    }

    // create the default web service configurator
    String pathToConfigFile = servletContext.getRealPath("/WEB-INF");
    AgentConfigurator defaultConfigurator = new AgentConfigurator(pathToConfigFile);
    TemplateActionsConfigurator templateActionsConfigurator = new TemplateActionsConfigurator(pathToConfigFile);
    List<Configurator> configurators = new ArrayList<Configurator>();
    configurators.add(defaultConfigurator);
    configurators.add(templateActionsConfigurator);

    log.info("Initializing ATS Agent web service, start component registration");

    try {
        MainComponentLoader.getInstance().initialize(configurators);
    } catch (AgentException ae) {
        throw new RuntimeException("Unable to initialize Agent component loader", ae);
    }
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:29,代码来源:AgentWsContextListener.java

示例12: input

import javax.servlet.ServletContext; //导入方法依赖的package包/类
@Override
public String input() throws Exception {
	HttpServletRequest request = Struts2Utils.getRequest();
	
	String fileName="site.properties";
	ServletContext sc = Struts2Utils.getSession().getServletContext();
	String filePath = "/WEB-INF/classes/conf/site/".replace("/", File.separator);
	String fileRealPath = sc.getRealPath("/")+filePath+fileName;
	File file=new File(fileRealPath);
	InputStreamReader fr = new InputStreamReader(new FileInputStream(file),"UTF-8");
	
	Properties p = new Properties();  
    try {
	    p.load(fr);
	    fr.close();

	   String adminEmail = p.getProperty("adminEmail");
	   String adminQQ = p.getProperty("adminQQ");
	   String adminTelephone = p.getProperty("adminTelephone");
	   String icpCode = p.getProperty("icpCode");
	   String tongjiCode = p.getProperty("tongjiCode");
	   String loginBgImg = p.getProperty("loginBgImg");

	   request.setAttribute("adminEmail", adminEmail);
	   request.setAttribute("adminQQ", adminQQ);
	   request.setAttribute("adminTelephone", adminTelephone);
	   request.setAttribute("icpCode", icpCode);
	   request.setAttribute("tongjiCode", tongjiCode);
	   request.setAttribute("loginBgImg", loginBgImg);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return INPUT;
}
 
开发者ID:wkeyuan,项目名称:DWSurvey,代码行数:35,代码来源:SysPropertyAction.java

示例13: uploadQrcode

import javax.servlet.ServletContext; //导入方法依赖的package包/类
@RequestMapping("/uploadQrcode")
public String uploadQrcode(@RequestParam("qrcode") MultipartFile qrcode, HttpServletRequest request) throws IOException {
    ServletContext servletContext = request.getServletContext();
    String qrcodeName = Long.toString(System.currentTimeMillis()) + qrcode.getOriginalFilename();
    String destPath = servletContext.getRealPath("/image/qrcode/") + qrcodeName;
    qrcode.transferTo(new File(destPath));

    int userId = getUserId();

    userBasicService.updateQrcode(userId, "/image/qrcode/" + qrcodeName, servletContext.getRealPath("/"));
    return "redirect:/settings";
}
 
开发者ID:qinjr,项目名称:TeamNote,代码行数:13,代码来源:UserController.java

示例14: getRealPath

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * Return the real path of the given path within the web application,
 * as provided by the servlet container.
 * <p>Prepends a slash if the path does not already start with a slash,
 * and throws a FileNotFoundException if the path cannot be resolved to
 * a resource (in contrast to ServletContext's {@code getRealPath},
 * which returns null).
 * @param servletContext the servlet context of the web application
 * @param path the path within the web application
 * @return the corresponding real path
 * @throws FileNotFoundException if the path cannot be resolved to a resource
 * @see javax.servlet.ServletContext#getRealPath
 */
public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	// Interpret location as relative to the web application root directory.
	if (!path.startsWith("/")) {
		path = "/" + path;
	}
	String realPath = servletContext.getRealPath(path);
	if (realPath == null) {
		throw new FileNotFoundException(
				"ServletContext resource [" + path + "] cannot be resolved to absolute file path - " +
				"web application archive not expanded?");
	}
	return realPath;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:28,代码来源:WebUtils.java

示例15: getBaseRealPath

import javax.servlet.ServletContext; //导入方法依赖的package包/类
/**
 * 通过ServletContext上下文获取应用绝对路径
 * 
 * @param request
 * @return 后面有File.separator
 */
public static String getBaseRealPath(HttpServletRequest request) {
	ServletContext servletContext = request.getSession().getServletContext();
	if (servletContext == null) {
		throw new NullPointerException("servletContext == null");
	}
	String realPath = servletContext.getRealPath("/");
	if (realPath == null) {
		throw new NullPointerException("servletContext.getRealPath(\"\") == null");
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("getBaseRealPath(HttpServletRequest request) realPath=" + realPath);
	}
	return toPath(realPath);
}
 
开发者ID:fier-liu,项目名称:FCat,代码行数:21,代码来源:PathUtil.java


注:本文中的javax.servlet.ServletContext.getRealPath方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。