【发布时间】:2012-06-17 02:22:32
【问题描述】:
我有一个 JAX-RS REST Web 应用程序,用于为桌面客户端存储和检索文件。我将在两个不同服务器上的两个不同环境中部署它,因此我希望在代码之外配置存储文件的路径。
我知道如何从 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;
}
}
}
【问题讨论】: