servlet之getRealPath获取路径问题。

Web中servlet开发利用getRealPath获取路径相关知识点总结:

在servlet开发中,经常会遇到这样一些问题。在获取web工程中的指定文件、URL时候,需要考虑路径该怎么写,以下是在servlet中分别获取:

web 工程目录下、src目录下、 webContent(WebRoot)目录下、WEB-INF目录下文件的过程。

为了更简单了解并区别不同目录的路径区别。先用JAVA SE IO流获取文件内容。为了演示效果,在工程下创建了四个TXT文件。

**********************************************************************************************************************************************************************************

文件目录结构:

servlet之getRealPath获取路径问题。_第1张图片


【1.】 使用Java SE IO 分别获取TXT文件

 public static void main(String[] args) throws IOException {
        
        //1.0 get the src.txt file 
        readFile("src/src.txt");
        
         //2.0 get the  webroot.txt file
        readFile("WebContent/webroot.txt");
        
        //3.0 get the web-info.txt
        readFile("WebContent/WEB-INF/webinfo.txt");
         
        //4.0 get the project.txt
        readFile("project.txt");
    }
    
    
    public static void readFile(String path) throws IOException{
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line = br.readLine();
        br.close();
        System.out.println("get the context in this file: " + line);
    }


输出结果:

get the context in file: this file is located in the src directory
get the context in file: this file is located in the webroot directory
get the context in file: this file is located in the web-info directory
get the context in file: this file is located in the webproject directory


=================================

本地eclipse和tomcat服务器上文件位置对应:

本地Eclipse中文件位置      ------------  服务器上文件位置(tomcat)
Web 工程下文件project.txt          无(访问不到404)
Src目录下src.txt                    /WEB-INF/classes/src.txt
WebRoot目录下webroot.txt         根目录 /webroot.txt
WEB-INF目录下webinfo.txt         /WEB-INF/webinfo.txt


【2.】 在servlet中使用getRealPath方法获取文件路径:

在servlet中分别获取TXT文件。通过ServletContext的getRealPath()方法,例如context.getRealPath(“/”);获取的是当前工程部署到tomcat服务器中的绝对磁盘路径。

具体代码内容如下:

     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        ServletContext context = this.getServletContext();

        String path = context.getRealPath("/"); // get the absolutely path of
                                                // web project in tomcat server.
        // System.out.println(path);

        // 1.0 get the src.txt file
        readFile(path + "WEB-INF/classes/src.txt");
        //== readFile(context.getRealPath("/WEB-INF/classes/src.txt"));

        // 2.0 get the webroot.txt file
        readFile(path + "webroot.txt");
        //== readFile(context.getRealPath("/webroot.txt"));

        // 3.0 get the web-info.txt
        readFile(path + "WEB-INF/webinfo.txt");
       //== readFile(context.getRealPath("/WEB-INF/webinfo.txt"));

    }



web开发中同时常用也可以用request域等其他域对象来获取路径,合理的选用最恰当的方式进行处理。





你可能感兴趣的:(servlet之getRealPath获取路径问题。)