将`init-param`从Guice传递给servlet

时间:2015-10-26 05:12:23

标签: java google-app-engine servlets guice jersey-2.0

尝试使用Guice(MyServletModule.java)将初始化参数传递给我的servlet:

    Map<String, String> params = new HashMap<>();
    params.put("key1", "value1");
    params.put("key2", "value2");
    this.serve("/hi").with(HelloWorldServlet.class, params);

然后尝试在我的servlet中打印出来:

    resp.setContentType("text/plain");
    resp.getWriter().println("Hello, my singleton AppEngine");

    resp.getWriter().println("key1: " + this.getServletContext().getInitParameter("key1"));

我总是得到null。我究竟做错了什么?我怀疑我将Guice Jersey与GAE集成是错误的,但无法对其进行故障排除。

文件:

配置:

  • Google App Engine for Java 1.9.26
  • Guice 4.0
  • 泽西岛2.5.1
  • Objectify 5.1.7

1 个答案:

答案 0 :(得分:1)

将以下内容添加到servlet中:

private String key1 = null;

private String key2 = null;


@Override
public void init(ServletConfig config) throws ServletException {
    this.key1 = config.getInitParameter("key1");
    this.key2 = config.getInitParameter("key2");
}

然后在doGet(...)方法中:

    resp.getWriter().println("key1: " + this.key1);
    resp.getWriter().println("key2: " + this.key2);