ServletContext常用方法1-获取全局参数和虚拟目录路径以及绝对路径

发布时间 2023-03-22 21:14:13作者: 唯?独爱你

 

public class ServletContextDemo extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取context对象
        ServletContext context = getServletContext();

        // 1、获取全局配置参数,根据key获取value
        String parameter = context.getInitParameter("globaEncoding");
        System.out.println(parameter);

        // 2、获取应用的虚拟目录
        String contextPath = context.getContextPath();
        System.out.println(contextPath);

        // 3、根据虚拟目录获取绝对路径
        // src目录下的文件
        String realPath1 = context.getRealPath("/WEB-INF/classes/a.txt");
        System.out.println(realPath1);
        // web目录下的文件
        String realPath2 = context.getRealPath("/b.txt");
        System.out.println(realPath2);
        // WEB-INF目录下的文件
        String realPath3 = context.getRealPath("/WEB-INF/web.xml");
        System.out.println(realPath3);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}