2012-06-14 5 views
0

데스크톱 클라이언트 용 파일을 저장하고 검색하는 데 사용되는 JAX-RS REST 웹 앱이 있습니다. 두 개의 다른 서버에있는 두 개의 서로 다른 환경에이를 배포 할 것이므로 파일이 저장 될 경로를 코드 외부에 구성하고 싶습니다.REST 리소스에서 서블릿 초기화 매개 변수에 액세스

서블릿에서 초기화 매개 변수 (web.xml)를 읽는 방법을 알고 있습니다. REST 리소스 클래스와 비슷한 것을 할 수 있습니까? WEB-INF 디렉토리 내의 다른 파일에서 읽을 수 있다면 잘 작동 할 것입니다. 당신이 당신의 나머지 자원

context.getInitParameter("praram-name") 

답변

0

첫째 : 여기

내가 함께 일하고 있어요 코드입니다 web.xml에서 init 매개 변수를 얻는 것이 일반적인 작업처럼 보입니다.이 작업의 맨 아래로 가려면 꽤 시간이 필요했습니다. 효과가있는 솔루션을 찾아보십시오. 저의 좌절감에서 다른 사람들을 구하기 위해 제 해결책을 게시하겠습니다. Jersey 구현을 사용 중입니다. com.sun.jersey.spi.container.servlet.ServletContainer 아마도 다른 REST 구현은 ServletContext을 사용하여 web.xml 초기화 매개 변수에 액세스 할 수 있지만 실제로 작동한다고 믿을 수있는 설명서가 있음에도 불구하고 그렇지 않습니다.

대신 다음을 사용해야합니다. @Context ResourceConfig context; 이것은 내 리소스 클래스의 필드 중 하나로 표시됩니다. 그럼 내 자원의 방법 중 하나에서, 나는 다음과 web.xml의 초기화 매개 변수에 액세스 할 수 있었다 :이 건물은 web.xml 파일을 참조

String uploadDirectory = (String) context.getProperty("dataStoragePath"); 

: 놀랍게도

<init-param> 
     <param-name>dataStoragePath</param-name> 
     <param-value>C:/ztestServer</param-value> 
    </init-param> 

, @Context ServletContext context;을 사용할 때 컨텍스트 개체가 실제로 ApplicationContextFacade를 참조했음을 발견했습니다. 나는 Facade를 통과 할 수있는 방법을 보지 못했고 내가 관심을 갖는 정보에 접근 할 수 없었다. 나는 매개 변수지도를 인쇄하고는 유일한 매개 변수는이 객체가 알고 있었다 저를 보여 주었다 :

java.util.Enumeration<String> params = context.getInitParameterNames(); 
    while(params.hasMoreElements()) 
     System.out.println(params.nextElement()); 

출력 :

com.sun.faces.forceLoadConfiguration 
com.sun.faces.validateXml 
+0

유일한 문제는 나중에 그것이 작동하지 않았 음을 발견 한 것입니다. – Thorn

+0

이것은 작동하지 않습니다. 이 경우의 컨텍스트는 Application Facade입니다. – gshauger

3

동안 내부에 그런

@Context 
ServletContext context; 

를 사용하여 서블릿 컨텍스트를 얻을 수있다

import javax.ws.rs.*; 
import java.io.*; 

@Path("/upload") 
public class UploadSchedule { 

    static String path = "/home/proctor/data/schoolData/"; 
    //I would like to store the path value in web.xml 
    @PUT 
    @Path("/pxml/{id}/") 
    @Consumes("text/xml") @Produces("text/plain") 
    public String receiveSchedule(@PathParam("id") final Integer schoolID, String content) { 
     if (saveFile(schoolID, "schedule.pxml", content)) 
      return schoolID + " saved assignment schedule." 
     else 
      return "Error writing schedule. ("+content.length()+" Bytes)"; 
    } 

    /** 
    * Receives and stores the CSV file faculty list. The location on the server 
    * is not directly associated with the request URI. 
    * @param schoolID 
    * @param content 
    * @return a String confirmation message. 
    */ 
    @POST 
    @Path("/faculty/{id}/") 
    @Consumes("text/plain")  @Produces("text/plain") 
    public String receiveFaculty(@PathParam("id") final Integer schoolID, String content) { 
     if (saveFile(schoolID, "faculty.csv", content)) 
      return schoolID + " saved faculty."; 
     else 
      return "Error writing faculty file.(" +content.length()+ " Bytes)"; 

    } 
    //more methods like these 

    /** 
    * Saves content sent from the user to the specified filename. 
    * The directory is determined by the static field in this class and 
    * by the school id. 
    * @param id SchoolID 
    * @param filename location to save content 
    */ 
    private boolean saveFile(int id, String filename, String content) { 
     File saveDirectory = (new File(path + id)); 
     if (!saveDirectory.exists()) { 
      //create the directory since it isn't there yet. 
      if (!saveDirectory.mkdir()) 
       return false; 
     } 
     File saveFile = new File(saveDirectory, filename); 
     try(FileWriter writer = new FileWriter(saveFile)) { 
      writer.write(content); 
      return true; 
     } catch (IOException ioe) { 
      return false; 
     } 
    } 
} 
관련 문제