如何以编程方式将我自己的ServletConfig传递给servlet

时间:2012-08-25 20:05:30

标签: jetty servlet-3.0

这是一个关于嵌入jetty 7的示例: http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty

public class OneServletContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        context.addServlet(new ServletHolder(new HelloServlet()),"/*");

        server.start();
        server.join();
    }
}

将通过调用init(ServletConfig config)来初始化服务器HelloServlet;

如何告诉Jetty将自己的ServletConfig传递给HelloServet? (我没有web.xml文件,我不想拥有一个)

Note:
I think that in Jetty6, you can call context.setInitParameter("my_key", "my_value");
but this function does not exists in Jetty7.

I've tried with context.getServletContext.setInitParameter("my_key", "my_value");
but I get an exception
java.lang.IllegalStateException was thrown.
org.eclipse.jetty.servlet.ServletContextHandler$Context.setInitParameter(ServletContextHandler.java:569)

1 个答案:

答案 0 :(得分:8)

解决:

ServletHolder helloServletHolder = new ServletHolder(new HelloServlet());
helloServletHolder.setInitParameter("my_key", "my_value");
context.addServlet(helloServletHolder,"/*");