我有一個用於存儲和檢索桌面客戶端文件的JAX-RS REST Web應用程序。我將在兩個不同的服務器上的兩個不同的環境中部署它,所以我希望將文件存儲的路徑配置在代碼之外。從REST資源訪問Servlet初始化參數
我知道如何從Servlet讀取初始化參數(在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;
}
}
}
唯一的問題是,我後來才發現,它沒有工作。 – Thorn
這不起作用。這種情況下的上下文是應用外觀 – gshauger