0

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" >

and not doing this

<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" >

I used this.

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

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.

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

2

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" >

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.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thank you. Then how i can manage, for instance, a link to a css. In every single jsp page i have to write ../ according to the number of subfolders the jsp page is put? – MDP Oct 03 '13 at 12:59
  • Just make use of templating and/or tagfiles to reduce repeated boilerplate into a single place. Or, move to JSP's successor Facelets which supports this all out the box. This is further completely unrelated to the concrete question/problem being asked. – BalusC Oct 03 '13 at 13:00