java web项目获取项目路径
2023-09-27 14:23:50 时间
注意:有时获取到的项目路径后再+“自定义路径后” 路径不可用,这时要看下项目里自定义路径是不是空文件夹,如果是空文件夹则调试和运行时文件夹不会编译到部署文件里.
1.方法一
调试时只能获取eclipse 项目未编译前的路径 不太好用
/* private static Logger logger = Logger.getLogger(BookController.class); */ @RequestMapping("/index") public String bookHandle(HttpServletRequest servlet) { JSONObject json = JsonResourceUtils.getJsonObjFromResource ("static/json/book_nav.json",servlet.getServletContext().getRealPath("/")); return "book"; }
2.方法 二
获取项目运行时的真实类路径
/* private static Logger logger = Logger.getLogger(BookController.class); */ @RequestMapping("/index") public String bookHandle(HttpServletRequest servlet) { JSONObject json = JsonResourceUtils.getJsonObjFromResource
/* 这里直接获取到了文件路径 */ (BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath()); 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"));
}
}
相关文章
- Java NIO 粘包 拆包 (实战) - 史上最全解读
- 【JAVA】Eclipse如何导入其他电脑中的项目?(图文,已解决!)
- Java获取项目路径
- Maven MyEclipse创建web项目没有src/maim/java
- Java基础-新建项目、包和类
- SSM实战项目——Java高并发秒杀API
- CentOS7 nginx+tomcat实现代理访问java web项目让项目支持jsp和php
- java 中的fork join框架
- eclipse java web项目导入到idea
- threw load() exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet(maven项目git后)
- java项目代码上线
- Java正則表達式入门
- 怎么部署java项目(从搭建环境说起)
- 对项目中所写的Java代码进行计数,看总共写了多少行代码???
- IDEA创建java项目并打包成jar包
- 电商系统 常用代码 Java