取得ServletContext实例

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,添加如下代码:


    
    ServletContextDemoServlet
    ServletContextDemoServlet
    im.weitang.ServletContextDemoServlet


    ServletContextDemoServlet
    /ServletContextDemoServlet

程序运行后,tomca后台输出:

真实路径:D:\JavaWeb\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\servlet\

你可能感兴趣的:(取得ServletContext实例)