Java(JSP/Servlet):等效于.jsp内部的getServletContext() [英] Java (JSP/Servlet): equivalent of getServletContext() from inside a .jsp
问题描述
如何从.jsp访问ServletContext?例如,如何从.jsp内部调用 getRealPath 方法.
How should I access the ServletContext from a .jsp? For example, how can I call the getRealPath method from inside a .jsp.
这是一个工作正常的Servlet:
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();
}
现在,我正在寻找要插入到以下 .jsp 中的确切行,以执行与上述servlet完全相同的操作.
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>
推荐答案
可通过application
隐式对象访问ServletContext
.
由于每个JSP都是servlet,因此您也可以使用getServletContext()
.
Since each JSP is a servlet, you can also use getServletContext()
.
但是..避免在JSP中使用类似的代码.取而代之的是,在Servlet中获取所需的值并将其设置为request属性,只需在JSP中读取即可(最好通过JSTL)
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)
这篇关于Java(JSP/Servlet):等效于.jsp内部的getServletContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!