Get root web application from Spring controller

I am trying to write the downloaded multi-page file to the file system. I have a directory called audio, which is located in the root of my web application (and not inside WEB-INF, but next to it, it is publicly accessible, for example, css and javascript).

I want to write the downloaded file to this directory, but I cannot find the path that I need. I thought getting ServletContext (), then using realPath () might work, but I don't have a reference to ServletContext through the Spring controller. Thanks for any hep

@RequestMapping(value="/uploadSample") public ModelAndView upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile f) { if (f == null) { return new ModelAndView("upload", "msg", "The file is null."); } try { // I need to set AUDIO_PATH to <webAppRoot>/audio FileOutputStream file = new FileOutputStream(AUDIO_PATH + "/" + f.getOriginalFilename()); file.write(f.getBytes()); file.close(); } catch (FileNotFoundException ex) { Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(SampleUploadController.class.getName()).log(Level.SEVERE, null, ex); } return new ModelAndView("upload", "msg", "File ( " + f.getOriginalFilename() + ") successfully uploaded."); } 

}

+12
java spring file-io
Jan 14 '10 at 19:16
source share
3 answers

I was thinking of getting ServletContext () then using realPath () might work, but I don't have a reference to ServletContext

Yes Yes. See HttpServletRequest.getSession (). GetServletContext ()

+11
Jan 14 '10 at 19:21
source share

To get a reference to ServletContext , your class can implement ServletContextAware

EDIT: ServletContext also available in a web application container called bean ServletContext , so you can enter it like any other bean in Spring.

+26
Jan 14 '10 at 19:21
source share

Retrieving a server URL using ServletContext unsafe in different environments.

Better get the url from the properties file.

0
Nov 13 '16 at 22:36
source share



All Articles