Passing initialization parameters to a servlet via annotations
Sometimes it is useful to pass some initialization parameters to a servlet. That way, we can make said servlet behave differently based on the parameters that are sent to it. For example, we may want to configure a servlet to behave differently in development and production environments.
In the old days, servlet initialization parameters were sent via the <init-param>
parameter in web.xml
. As of servlet 3.0, initialization parameters can be passed to the servlet as the value of the initParams
attribute of the @WebServlet
annotation. The following example illustrates how to do this:
package com.ensode.jakartaeebook.initparams; //imports omitted for brevity @WebServlet(name = "InitParamsServlet", urlPatterns = { "/InitParamsServlet"}, initParams = { @WebInitParam(name = "param1", value = "value1"), @WebInitParam(name = "param2"...