I've embedded Jetty, and I'm trying to set an initialization parameter.
The main class Main creates a servlet of Cgi which extends CGI.
Within Main, I have the following code:
ServletContextHandler context2 = new ServletContextHandler(ServletContextHandler.SESSIONS);
context2.setContextPath("/cgi");
context2.setResourceBase("./cgi-bin");
context2.setInitParameter("commandPrefix", "perl");
context2.addServlet(new ServletHolder(new Cgi()), "/");
server.setHandler(context2);
Within Cgi, I check to see the parameter:
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println(servletConfig.getInitParameter("commandPrefix"));
super.init(servletConfig);
}
Each time, it prints out null for the getInitParameter call. Then when the Cgi does indeed NEED to use this, it doesn't, because it's not set. Why could this be happening?
You're setting the InitParameter on the ServletContextHandler
, but you should be setting it on the ServletHolder
.
(It's somewhat confusing, I know)
You've set a context init parameter, not a servlet init parameter. So you need to retrieve it as a context init parameter instead of as a servlet init parameter.
System.out.println(servletConfig.getServletContext().getInitParameter("commandPrefix"));
Alternatively, you can of course also set it as a servlet init parameter instead, but this way the parameter will only be available to the associated servlet only, not to all other servlets running in the same context. This may or may not be what you want, depending on the concrete functional requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With