[英]how to get web context path in spring mvc + maven project?
我正在使用tomcat7-maven-plugin啟動我的spring mvc項目,並嘗試通過下面的方法獲取spring控制器中的fullpath。
String path = this.getClass().getClassLoader().getResource("").getPath();
它將為我提供如下路徑。
C:/Users/xxxxx/Documents/xxx/apache-tomcat-8.5.31/webapps/showcase/WEB-INF/classes/
然后,我可以通過fullPath.split("/WEB-INF/classes/")
獲得上下文路徑。 實際上,它與springmvc無關,如果無法獲取ServletContext,則任何Java Web應用程序都可以獲取這樣的上下文路徑。
但是如果我通過' mvn tomcat7:run '在dev模式下啟動項目。 它將為我提供如下路徑。
C:/git/xxxxx/showcase/target/classes
然后,我無法通過該URL獲取上下文路徑。 我想知道通過Maven啟動項目時上下文根在哪里,如何獲得它? 謝謝。
public static File upload(MultipartFile file, HttpServletRequest request, boolean file_name, String upload_folder) {
String filename = null;
File serverFile = null;
try {
String applicationpath = request.getServletContext().getRealPath("");
filename = file.getOriginalFilename();
byte[] bytes = file.getBytes();
String rootPath = applicationpath;
File dir = new File(rootPath + File.separator + upload_folder);
if (!dir.exists())
dir.mkdirs();
serverFile = new File(dir.getAbsolutePath() + File.separator + filename);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
return serverFile;
} catch (Exception e) {
serverFile = null;
}
return serverFile;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.