我想在我的web项目的根路径上创建一个临时文件夹来上传文件。我一派,使用:如何在SpringMVC中获取Web项目的根路径?
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void torrent2magnet(HttpSession session) {
String uploadBaseDir = session.getServletContext().getRealPath("/")+File.separator+"uploadFiles"+File.separator;
}
可以获取到Web项目的相对路径。 但有2个障碍如下:
1:session.getServletContext().getRealPath("/")
可以在使用不同的容器(如tomcat或weblogic)时采取不同的行为。在最坏的情况下,它可能会返回null
。
2:我打算编写一个@Service
类,其中将提供一个方法来返回当前Web项目的根路径。我如何在@Service
类中获得ServletContext
实例?
有没有更好的方法来解决这两个问题?非常感谢!
你为什么不提供绝对路径到Web应用程序根目录作为一个可配置参数属性文件,数据库字段或环境变量。 – shazin