Java (JSP/Servlet):相当于 .jsp 中的 getServletContext()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2898390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java (JSP/Servlet): equivalent of getServletContext() from inside a .jsp
提问by SyntaxT3rr0r
How should I access the ServletContext from a .jsp? For example, how can I call the getRealPathmethod from inside a .jsp.
我应该如何从 .jsp 访问 ServletContext?例如,如何从 .jsp 内部调用getRealPath方法。
Here's a Servlet, which works fine:
这是一个 Servlet,它工作正常:
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 .jspto do exactly the same thing as the servlet above is doing.
现在我正在寻找我应该在下面的.jsp 中插入的确切行,以执行与上面的 servlet 所做的完全相同的事情。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
... // What should I insert here
</body>
</html>
采纳答案by Bozho
The ServletContext
is accessible via the application
implicit object.
该ServletContext
是通过访问application
隐含对象。
Since each JSP is a servlet, you can also use getServletContext()
.
由于每个 JSP 都是一个 servlet,因此您还可以使用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)
但是.. 避免在 JSP 中使用类似的代码。相反,在您的 servlet 中获取您需要的值并将其设置为请求属性,只需在 JSP 中读取它(最好通过 JSTL)
回答by Roman
Try this:
尝试这个:
${pageContext.servletContext}
回答by Mr.Expert
I think this should work fine on a JSP Page:
我认为这在 JSP 页面上应该可以正常工作:
<body>
<%
out.print(getServletContext().getAttribute("attribute"));
%>
</body>
回答by chris
if you're looking to use the getRealPath() method, you might consider looking into a jstl tag called 'c:url'
如果您想使用 getRealPath() 方法,您可以考虑查看名为“c:url”的 jstl 标记
<c:url value="text/en" />
回答by Mahmoud Abou-Eita
Simply use application.getRealPath(" ");
.
只需使用application.getRealPath(" ");
.