Change WebInitParam in Servlet 3.0 when project packaged in WAR

In my project, I am using Servlet 3.0, and I tried using annotations.

To initialize the connection parameters for the database, I use this in my servlet:

@WebServlet(name = "FrontServlet", urlPatterns = {"/index"}, initParams = { @WebInitParam(name = "userDB", value = "root"), @WebInitParam(name = "passwordDB", value = "*****")}) 

Now that I have packaged the project in WAR, I do not have web.xml, so I cannot edit the init parameters, as I did with the older version of the servlet.

My question is, can I change the initialization parameters when the project is packaged in WAR? If so, how? Otherwise, what approach should be used to store init parameters and the possibility of modifying them in the WAR?

If possible, I would like to avoid re-creating the entire web.xml with all the URL patterns, etc.

EDIT:

Finally, I saved:

 @WebServlet(name = "FrontServlet", urlPatterns = {"/index"}) 

And I load the DB parameters using Properties , accessing the configuration file using getClass().getClassLoader().getResourceAsStream("servlet/config/config.ini")

+4
source share
2 answers

AFAIK there is no standard way to change init parameters at runtime. Moreover, it is bad practice to place the configuration there, especially in order to add database credentials to clear text.

It is usually best to use the configuration in an external file. It can be some custom properties or an xml file.

To connect to a database, it is common to use JNDI. Thus, basically in the code you are looking for a JNDI resource, while JNDI itself is configured at the container level. Google to find many examples of how to set up a database connection through JNDI for Jetty, Tomcat, JBoss, etc.

+2
source

In Servlet 3.0, annotations provide default values, but they can be overloaded in web.xml, so you can add the following to web.xml to change the settings.

  <servlet> <servlet-name>FrontServlet</servlet-name> <servlet-class>fully.qualified.ClassName</servlet-class> <init-param> <param-name>passwordDB</param-name> <param-value>NewValue</param-value> </init-param> </servlet> 

In Tomcat, at least you need to specify the class name and servlet name. Without further study of code merging (since I worked on it), one of them should be enough. For now, you need to use both.

+4
source

Source: https://habr.com/ru/post/1411476/


All Articles