デスクトップクライアントのファイルを保存および取得するために使用される 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;
}
}
}