简体   繁体   中英

How to get the root path of a web project in SpringMVC?

I'd like to create a temporary folder at the root path of my web project for uploading files. I've googled that using:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void torrent2magnet(HttpSession session) {
    String uploadBaseDir = session.getServletContext().getRealPath("/")+File.separator+"uploadFiles"+File.separator;
}

can get a relative path to the web project. But there are 2 obstacles as follows:

1: session.getServletContext().getRealPath("/") can act differently when using different containers (like tomcat or weblogic). In the worst case, it may return null .

2: I intend to write a @Service class, in which a method will be provided to return the root path of current web project. how can I get a ServletContext instance in my @Service class?

Is there a more elegant way to resolve this two problems? Thanks a lot!

Just Implement ServletContextAware interface to get the ServletContext injected automatically. Override the setServletContext method. Please follow the link

One more advice is that please have your upload directory outside your application.that's always a good design

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM