stcaac 发表于 2017-2-1 13:54:24

日记

为了程序可在任意路径部署,这种动态的获取是十分必要的,让程序自动自己去获得tomcat的路径,而不是写死的,更加灵活方便。

String path = null;
      File file = new File(".");
      try {
            path = file.getCanonicalPath();
      } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
      }

以上代码获得的path是tomcat的bin目录

String s=request.getRealPath("/");

这个简短的代码获得的是tomcat将你工程编译后的路径,由于我用的是idea这款IDE工具,所以我的路径是在我工程目录下的target文件夹内,如果是myeclipse一般都是在tomcat的webapps文件夹里


顺便做列举一下可用的api的结果集:
      StringBuffer realPath1 = request.getRequestURL();
      String realPath2 = request.getContextPath();
      String realPath3 = request.getRealPath("/");
      String realPath4 = request.getServletPath();
      String projectUrl = System.getProperty("user.dir");

      realPath1 :http://localhost:8080/eventslin-api/test
      realPath2 :/eventslin-api
      realPath3 :D:\IdeaProjects\eventslin\eventslin-api\target\eventslin-api\
      realPath4 :/test
      projectUrl :D:\java\apache-tomcat-7.0.53\bin
      projectUrl :(如果是在main方法里使用,地址为当前工程根目录)
页: [1]
查看完整版本: 日记