我想在我的网络项目的根路径创建一个临时文件夹用于上传文件。我用谷歌搜索过:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void torrent2magnet(HttpSession session) {
String uploadBaseDir = session.getServletContext().getRealPath("/")+File.separator+"uploadFiles"+File.separator;
}
可以获得web项目的相对路径。 但是有两个障碍如下:
1: session.getServletContext().getRealPath("/")
在使用不同容器(如 tomcat 或 weblogic)时可能会采取不同的行为。在最坏的情况下,它可能返回null
。
2:我打算编写一个@Service
类,其中将提供一个方法来返回当前Web项目的根路径。如何在我的 @Service
类中获取 ServletContext
实例?
有没有更优雅的方法来解决这两个问题?非常感谢!
最佳答案
只需实现ServletContextAware
接口(interface)即可自动注入(inject)ServletContext。重写 setServletContext 方法。请关注link
还有一个建议是,请将上传目录放在应用程序之外。这始终是一个很好的设计
关于java - Spring MVC中如何获取Web项目的根路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19997862/