spring中获取当前项目的真实路径

📝 ✏️ 📌
spring中获取当前项目的真实路径

如果为体现项目的层次感,当我们使用request的时候,一般都是在控制层中使用的,没有必要将request也传递到service使用,所以首先是讲一下在controller获取当前的项目的绝对路径

public Message uploadImgsFile(HttpServletRequest request) {

//1

String realPath = request.getSession().getServletContext().getRealPath(File.separator);

System.out.println(realPath);

//2

String realPath2 = request.getServletContext().getRealPath(File.separator);

System.out.println(realPath2);

return null;

}

如果当前想要获取当前项目的绝对路径,而此时又不在controller,同时又不想传递request的参数到service层,可以这样操作

//代码片段

//现获取当前的路径

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

ServletContext servletContext = webApplicationContext.getServletContext();

String realPath = servletContext.getRealPath(File.separator);

System.out.println(realPath);

经过上面的操作可以获取项目的路径,以此来方便自己项目的需求

。。。。。。。。。。。。。。。。

方法2:

转:

在java类中获取WEB-INF路径

lunabird

2016.04.29 14:36* 字数 189 阅读 4699评论 0喜欢 5

把java项目部署到tomcat中以后,类文件的路径都在“apache-tomcat-7.0.69\webapps\APP\WEB-INF\classes”中,如果我们需要在某个java类中获取WEB-INF下的某些资源,例如现在我需要在WEB-INF下的templates文件夹下的模板资源

Paste_Image.png

就需要在java文件中这样获取classes目录,然后转到templates目录下。

private static String templatePath = TemplateFactory.class.getClassLoader().getResource("/").getPath().replace("classes", "templates");

其中TemplateFactory是我的Java类名,

TemplateFactory.class.getClassLoader().getResource("/").getPath()

是获取到classes文件夹下的路径,就是apache-tomcat-7.0.69\webapps\APP\WEB-INF\classes,

然后可以把classes替换为我们想要得到的文件夹名字。

参考:web项目中各种路径的获取

🔗 相关推荐

✨ 💡 🎯
精子在手上可以存活多久?
bt365体育网址

精子在手上可以存活多久?

📅 07-22 👀 7446
苹果自带百度在哪里?
365bet体育投注站

苹果自带百度在哪里?

📅 07-13 👀 2615
出国剩的外币怎么兑换人民币?外币可以直接去银行换吗?

🎈 和我们一起探索精彩世界 🎈