码迷,mamicode.com
首页 > 其他好文 > 详细

项目中路径问题

时间:2019-07-01 15:45:00      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:stat   内容   system   color   webapp   java   int   read   void   

    public static String getPath() {
        //得到当前的classpath的绝对路径的URI表示法
        String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
        //  将/换成\  去掉file:   //去掉classes\   去掉第一个\,如 \D:\JavaWeb...
        path=path.replace(‘/‘, ‘\\‘).replace("file:", "").replace("classes\\", "").substring(1); 
        return path;
    }
    
    //获得项目绝对路径
    public static String getProjectRootPath(){   
        String rootPath=Thread.currentThread().getContextClassLoader().getResource("").getPath();    
        rootPath = rootPath.substring(1,rootPath.indexOf("WEB-INF"));    
        return rootPath;
    }

classpath:只能服务器才能使用。客户端不能访问这个路径下的内容。

例如:项目名是test

D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/WEB-INF/classes/   
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/ 

@Autowired
    private HttpServletRequest request;
    @Test
    public void testUrl(){
        String schema = request.getScheme();
        String serverName = request.getServerName();
        // 端口号返回的是int类型
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        System.out.println("协议:"+schema);
        System.out.println("服务器名称:"+ serverName);
        System.out.println("服务器端口号:"+ serverPort);
        System.out.println("项目名称:"+ contextPath);
        System.out.println("servlet路径:"+ servletPath);
    }

 


项目中路径问题

标签:stat   内容   system   color   webapp   java   int   read   void   

原文地址:https://www.cnblogs.com/bulrush/p/11114330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!