java web項目獲取項目路徑


 

1.方法一,獲取項目運行時的真實類路徑

/* private static Logger logger = Logger.getLogger(BookController.class); */
    @RequestMapping("/index")
    public String bookHandle(HttpServletRequest servlet) {
        
        //項目路徑
        String filePath3 = request.getServletContext().getRealPath("/");
        System.out.println(filePath3);
        
        return "book";
    }

2.方法 二,獲取項目運行時的真實類路徑

/* private static Logger logger = Logger.getLogger(BookController.class); */
    @RequestMapping("/index")
    public String bookHandle(HttpServletRequest servlet) {
        
        String filePath4 = BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath();
        System.out.println(filePath4);
        
        return "book";
    }

 

 3.用spring 獲取運行時類路徑路徑

String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath();

4.其它方法

package com.demo;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.io.File;
 
 
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@RestController
public class Application {
     
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
     
    @GetMapping("/lujing")
    public void getLujing() throws Exception{
        //當前項目下路徑
        File file = new File("");
        String filePath = file.getCanonicalPath();
        System.out.println(filePath);
 
        //當前項目下xml文件夾
        File file1 = new File("");
        String filePath1 = file1.getCanonicalPath()+File.separator+"xml\\";
        System.out.println(filePath1);
 
        //獲取類加載的根路徑
        File file3 = new File(this.getClass().getResource("/").getPath());
        System.out.println(file3);
 
        //獲取當前類的所在工程路徑
        File file4 = new File(this.getClass().getResource("").getPath());
        System.out.println(file4);
 
        //獲取所有的類路徑 包括jar包的路徑
        System.out.println(System.getProperty("java.class.path"));
    }
}

 

 

 

轉: https://www.cnblogs.com/jiangfeilong/p/11106129.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM