简体   繁体   中英

Java: How do I add properties from a database to a ResourceBundle on runtime?

Background

I am developing a Java Web Application using Maven. I have created ResourceBundles in this path and format: src/main/resources/i18n/LanguageBundle_xx_XX.properties .

Everything works perfectly and I have everything working on the front end (using JSTL).

Problem

The user can create KEY/VALUE pairs, from the front end, that are then stored in a MySQL database in the format: KEY | VALUE

I have a initializing servlet that does all the setting up before taking the user to the first jsp page.

In that initializing servlet I am getting all the KEY/VALUE pairs from the database, but now I want to add them to the LanguageBundle so that translations are ready when the first jsp page is presented.

I've tried so far:

  1. Returning all the key/value pairs from the DB
  2. Iterating the values returned
  3. If KEY doesn't exist in LanguageBundle_xx_XX
  4. Add the KEY/VALUE with property.put("KEY","VALUE")

Now, that does add the property, however if I try to access that specific property outside that scope (eg, other servlets, jsp), it fails as it doesn't exist in the specific .properties file.

How do I solve this problem?

UPDATE:

I have come up with a solution that works.

Properties prop = new Properties();
    InputStream in = getClass().getResourceAsStream("/i18n/LanguageBundle_en_US.properties");
    prop.load(in); 
prop.setProperty("KEY", "VALUE");
in.close();
prop.store(new FileOutputStream(getClass().getClassLoader().getResource("/i18n/LanguageBundle_en_US.properties").getFile()), null);

Can someone tell me if this is bad practice or is it fine to use?

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM