0

デスクトップクライアントのファイルを保存および取得するために使用される JAX-RS REST Web アプリがあります。これを 2 つの異なるサーバー上の 2 つの異なる環境にデプロイするので、ファイルが保存されるパスをコードの外部で構成したいと思います。

サーブレットから初期化パラメーター (web.xml 内) を読み取る方法を知っています。REST リソース クラスに対して同様のことを行うことはできますか? WEB-INF ディレクトリ内の他のファイルから読み取ることができれば、それも正常に機能するはずです。

ここに私が取り組んでいるコードがあります:

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;
        } 
    }
}
4

2 に答える 2

3

web.xmlからinitパラメーターを取得することは一般的な作業のように思えますが、これの根底に到達して機能する解決策を見つけるのにかなりの時間がかかりました。私の欲求不満から他の人を救うために、私の解決策を投稿させてください。私はJersey実装を使用しています。つまり、 com.sun.jersey.spi.container.servlet.ServletContainer おそらく他のREST実装はを使用してweb.xml init paramsにアクセスできますServletContextが、これが機能すると信じるドキュメントがあるにもかかわらず、機能しませんでした。

代わりに次を使用する必要がありました。@Context ResourceConfig context; これは、Resourceクラスのフィールドの1つとしてリストされています。次に、リソースメソッドの1つで、次のコマンドを使用してweb.xmlinitパラメーターにアクセスできました。

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

プロパティがweb.xmlファイルを参照している場合:

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

驚いたことに、私が使用したとき@Context ServletContext context;、コンテキストオブジェクトが実際にApplicationContextFacadeを参照していることを発見しました。そのファサードを通り抜けて、気にかけている情報にアクセスする方法がわかりませんでした。パラメータマップを印刷したところ、このオブジェクトが認識しているパラメータは次のとおりであることがわかりました。

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

出力:

 com.sun.faces.forceLoadConfiguration
 com.sun.faces.validateXml
于 2012-07-14T01:46:25.173 に答える
0

まず、次を使用してサーブレット コンテキストを取得する必要があります。

@Context 
ServletContext context;

次に、残りのリソース内で

context.getInitParameter("praram-name")
于 2012-06-14T05:53:05.727 に答える