복붙노트

[SPRING] Spring Controller에서 Web App 루트 얻기

SPRING

Spring Controller에서 Web App 루트 얻기

파일 시스템에 업로드 된 멀티 파트 파일을 쓰려고합니다. 나는 내 웹 응용 프로그램의 루트에 앉아있는 audio라는 디렉토리를 가지고 있습니다 (WEB-INF 안이 아니라 옆에 CSS와 javascript처럼 공개적으로 액세스 할 수 있음).

그 디렉토리에 업로드 된 파일을 쓰고 싶지만 필요한 경로를 얻을 수없는 것 같습니다. 나는 ServletContext ()를 얻고 나서 realPath ()를 사용하는 것이 효과가있을 것이라고 생각했지만 Spring 컨트롤러를 통해 ServletContext에 대한 참조를 가지고 있지 않다. 모든 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.");
}

}

해결법

  1. ==============================

    1.네, 그렇습니다. HttpServletRequest.getSession (). getServletContext ()를 참조하십시오.

    네, 그렇습니다. HttpServletRequest.getSession (). getServletContext ()를 참조하십시오.

  2. ==============================

    2.ServletContext에 대한 참조를 얻으려면 클래스가 ServletContextAware

    ServletContext에 대한 참조를 얻으려면 클래스가 ServletContextAware

    편집 : ServletContext는 웹 애플리케이션 컨테이너에서 bean 이름 servletContext로 액세스 할 수 있으므로 다른 빈처럼 Spring에 삽입 할 수있다.

  3. ==============================

    3.ServletContext를 사용하여 서버 URL을 얻는 것은 다른 환경에서 안전하지 않습니다.

    ServletContext를 사용하여 서버 URL을 얻는 것은 다른 환경에서 안전하지 않습니다.

    속성 파일에서 URL을 검색하는 것이 좋습니다.

  4. from https://stackoverflow.com/questions/2066843/get-web-app-root-from-spring-controller by cc-by-sa and MIT license