application内置对象是ServletContext接口的实例,表示的是Servlet上下文。如果要在一个Servlet中使用此对象。直接通过GenericServlet类提供的方法即可。
ServletContextDemoServlet.java
package im.weitang;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext app = super.getServletContext();
System.out.println("真实路径:" + app.getRealPath("/"));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
修改Web.xml,添加如下代码:
<servlet>
<description></description>
<display-name>ServletContextDemoServlet</display-name>
<servlet-name>ServletContextDemoServlet</servlet-name>
<servlet-class>im.weitang.ServletContextDemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemoServlet</servlet-name>
<url-pattern>/ServletContextDemoServlet</url-pattern>
</servlet-mapping>
程序运行后,tomca后台输出:
真实路径:D:\JavaWeb\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\servlet\