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

点点圈 提交于 2019-12-30 18:43:08

问题


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>

回答1:


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)




回答2:


Try this:

${pageContext.servletContext}



回答3:


I think this should work fine on a JSP Page:

<body>
<%
out.print(getServletContext().getAttribute("attribute"));
%>
</body>



回答4:


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



回答5:


Simply use application.getRealPath(" ");.



来源:https://stackoverflow.com/questions/2898390/java-jsp-servlet-equivalent-of-getservletcontext-from-inside-a-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!