如何知道真实的道路 [英] How to know the realpath

查看:75
本文介绍了如何知道真实的道路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个带有一些子文件夹的小站点. 我不知道一个jsp页面将有多少个子页面,所以我需要一种方法来了解我的Web应用程序的真实路径,以便执行以下操作:

i'm building a little site with some subfolders. I dunno in how many subfoler a jsp page will be, so i need a way to know the realpath of my web pplication, in order to do something like this:

<link rel="stylesheet" type="text/css" href="<%=realpath%>/Style.css" >

不要这样做

<link rel="stylesheet" type="text/css" href="../Style.css" >
<link rel="stylesheet" type="text/css" href="../../Style.css" >
<link rel="stylesheet" type="text/css" href="../../../Style.css" >

我用了这个.

ServletContext context = session.getServletContext();
String path = getServletContext().getRealPath("/");

但是,即使路径似乎是正确的(在屏幕上打印时),当我打开jsp页面时,也找不到CSS.

But it doesn't work, even if the path seems to be right (when i print it on the screen), when i open the jsp page my CSS is not found.

推荐答案

您在犯一个概念性错误. web浏览器在解析检索到的HTML输出时通过URL下载CSS文件,而不是通过服务器通过磁盘文件系统路径以某种方式魔术地内联,同时产生您似乎认为的HTML输出.因此,整个真实路径"方法是错误的.您应该准备一个有效的URL.如果您关心上下文路径的动态性,只需使用HttpServletRequest#getContextPath()动态打印上下文路径即可.

You're making a conceptual mistake. CSS files are downloaded by webbrowser through an URL while parsing the retrieved HTML output, not somehow magically inlined by webserver through disk file system path while producing the HTML output as you seem to think. So the whole "realpath" approach is wrong. You should be preparing a valid URL. If the dynamicness of the context path is your concern, just use HttpServletRequest#getContextPath() to dynamically print the context path.

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/Style.css" >

也就是说,在我使用Java EE的十多年中,没有任何明智的商业理由使用ServletContext#getRealPath().只是根本不使用它.这样做的任何尝试毕竟是最有可能的明显错误.

That said, in the more than a decade I worked with Java EE, there was no single sensible business reason to use ServletContext#getRealPath(). Just don't use it at all. Any attempt to do so is after all most likely plain wrong.

  • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
  • What does servletcontext.getRealPath("/") mean and when should I use it

这篇关于如何知道真实的道路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆