繁体   English   中英

从REST资源访问Servlet初始化参数

[英]Accessing a Servlet Initialization Parameter from REST resource

我有一个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;
        } 
    }
}

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

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

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。 我看不到有任何途径可以访问该Facade并访问我关心的信息。 我打印了参数图,它显示出该对象知道的唯一参数:

    java.util.Enumeration<String> params = context.getInitParameterNames();
    while(params.hasMoreElements())
        System.out.println(params.nextElement());

输出:

 com.sun.faces.forceLoadConfiguration
 com.sun.faces.validateXml

首先,您必须使用

@Context 
ServletContext context;

然后在您的休息资源中

context.getInitParameter("praram-name")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM