【问题标题】:Accessing a Servlet Initialization Parameter from REST resource从 REST 资源访问 Servlet 初始化参数
【发布时间】: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;
        } 
    }
}

【问题讨论】:

    标签: java rest servlets


    【解决方案1】:

    虽然从 web.xml 获取初始化参数似乎是一项常见任务,但我花了相当长的时间才深入了解并找到可行的解决方案。为了让其他人免于沮丧,让我发布我的解决方案。我正在使用 Jersey 实现,即 com.sun.jersey.spi.container.servlet.ServletContainer 也许其他 REST 实现可以使用 ServletContext 访问 web.xml 初始化参数,但尽管有文档让我相信这会起作用,但它没有。

    我需要改用以下内容:@Context ResourceConfig context; 这被列为我的资源类中的字段之一。然后在我的一种资源方法中,我能够使用以下内容访问 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
    

    【讨论】:

      【解决方案2】:

      首先您必须使用

      获取 servlet 上下文
      @Context 
      ServletContext context;
      

      然后在你的休息资源里面

      context.getInitParameter("praram-name")
      

      【讨论】:

      • 唯一的问题是后来发现不行。
      • 这不起作用。本例中的上下文是应用程序外观
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      相关资源
      最近更新 更多