Java – how to modify the web environment entry in GlassFish 4
On my web In XML, my webapp application has the following elements:
<env-entry> <env-entry-name>aMessage</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Hello World</env-entry-value> </env-entry>
EJBs in this web application can read it:
final InitialContext context = new InitialContext(); final Context env = (Context) context.lookup("java:comp/env"); System.out.println("MSG: " + env.lookup("aMessage")); // prints Hello World
Now I try to change this value with asadmin:
martin@bono:~/glassfish4/glassfish/bin$./asadmin set-web-env-entry --name=aMessage --value=test webapp PrevIoUs env-entry setting of aMessage for application/module webapp was overridden. Command set-web-env-entry executed successfully. martin@bono:~/glassfish4/glassfish/bin$./asadmin list-web-env-entry webapp Reported 1 env-entry setting aMessage (java.lang.String) = test ignoreDescriptorItem=true // Command list-web-env-entry executed successfully.
Unfortunately, even after re enabling this webapp or restarting the web server, my EJB still prints the old value "Hello world"
I also tried to create a web The web env entry is set with an undefined name in XML, and it is also set with the – ignoredescriptoritem parameter, but it does not help Enumerating the entire environment does not show any additional or changed web environment entries, but shows his old plus many other objects unrelated to this problem:
final NamingEnumeration<Binding> enu = env.listBindings(""); while (enu.hasMore()) { final Binding binding = enu.next(); System.out.println(binding); }
What did I do wrong?
Solution
It seems like a mistake - but I have another solution to meet your needs You can use the custom resources provided in GlassFish You must be in domain Declare custom resources in XML
<resources> <custom-resource factory-class="org.glassfish.resources.custom.factory.PropertiesFactory" res-type="java.util.Properties" jndi-name="test/properties"> <property name="aMessage" value="Hello World"></property> </custom-resource> </resources>
Then you can use it in your code
public class Environment { public String getproperty() { InitialContext ctx = new InitialContext(); properties = (Properties) ctx.lookup("test/properties"); if(properties == null) { return "default value - hello"; } return properties.getProperty("aMessage"); } }
One disadvantage of this approach is that custom resources are global to the entire domain However, this solution has advantages. You can change resources by using asadmin and admin web console