7

How should I access the ServletContext from a .jsp? For example, how can I call the getRealPath method from inside a .jsp.

Here's a Servlet, which works fine:

protected void doGet(
            HttpServletRequest req,
            HttpServletResponse resp
    ) throws ServletException, IOException {
        resp.setContentType( "text/html; charset=UTF-8" );
        final PrintWriter pw = resp.getWriter();
        pw.print( "<html><body>" );
        pw.print( getServletContext().getRealPath( "text/en" ) );
        pw.print( "</body></html>" );
        pw.flush();
        pw.close();
    }

Now I'm looking for the exact line I'm supposed to insert in the following .jsp to do exactly the same thing as the servlet above is doing.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <body>
     ...  // What should I insert here   
  </body>
</html>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
SyntaxT3rr0r
  • 27,745
  • 21
  • 87
  • 120

5 Answers5

14

The ServletContext is accessible via the application implicit object.

Since each JSP is a servlet, you can also use getServletContext().

But.. avoid having code like that in the JSP. Instead, obtain the value you need in your servlet and set it as a request attribute, simply reading it in the JSP (via JSTL preferably)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
11

Try this:

${pageContext.servletContext}
Roman
  • 64,384
  • 92
  • 238
  • 332
  • From the question: *"For example, how can I can call the getRealPath() method from inside a .jsp"*? – SyntaxT3rr0r May 24 '10 at 16:18
  • 1
    @Webinator: that method requires a String parameter so you cannot call it through `${}` notation. There are at least 3 different approaches exist: 1)You can call this method inside a bean (the best for the case IMHO) 2) You can create a custom tag and call it from there 3) You can write a scriplet (`<% //some code here %>`) - the worst IMHO. – Roman May 24 '10 at 16:23
3

Simply use application.getRealPath(" ");.

peterh
  • 11,875
  • 18
  • 85
  • 108
Mahmoud Abou-Eita
  • 933
  • 1
  • 8
  • 17
3

I think this should work fine on a JSP Page:

<body>
<%
out.print(getServletContext().getAttribute("attribute"));
%>
</body>
Mr.Expert
  • 466
  • 2
  • 3
2

if you're looking to use the getRealPath() method, you might consider looking into a jstl tag called 'c:url'

<c:url value="text/en" />
chris
  • 9,745
  • 1
  • 27
  • 27