Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (JSP/Servlet): equivalent of getServletContext() from inside a .jsp

Tags:

java

jsp

servlets

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>
like image 504
SyntaxT3rr0r Avatar asked May 24 '10 16:05

SyntaxT3rr0r


People also ask

What is Getservletcontext in Java?

Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

Which of the following is equivalent to out print () method in JSP?

The code placed within JSP expression tag is written to the output stream of the response. So you need not write out. print() to write data.

Which of the following JSP tag is most suitable to write the Java code inside the HTML of JSP page?

Scriptlet tag allows to write Java code into JSP file.


1 Answers

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)

like image 143
Bozho Avatar answered Oct 05 '22 04:10

Bozho