0

I have a JAX-RS REST web app that is used to store and retrieve files for a desktop client. I will be deploying this in two different environments on two different servers, so I would like the path where the files will be stored to be configured outside of the code.

I know how to read initialization parameters (in web.xml) from a Servlet. Can I do something similar for a REST resource class? If I could read from some other file inside the WEB-INF directory, that should work fine too.

Here is the code I'm working with:

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 初始化参数,ServletContext但尽管有文档让我相信这会起作用,但它没有。

我需要改用以下内容:@Context ResourceConfig context; 这被列为我的 Resource 类中的字段之一。然后在我的一种资源方法中,我能够使用以下内容访问 web.xml 初始化参数:

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

首先,您必须使用 servlet 上下文

@Context 
ServletContext context;

然后在你的休息资源中

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