Search code examples
jakarta-eeweb.xmljava-ee-7

Environmental Entry - Java EE - Web.XML - Null Value Returned


I am trying to retrieve the value from an Environment Entry in a web.xml file in my Java EE Web application. I am using Netbeans with a Glassfish server...

Here is my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"         
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<env-entry>
    <description>This example uses @Resource()</description>
    <env-entry-name>com.stuff.PasswordSessionBean/password</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>SteveJobbs</env-entry-value>
</env-entry>

<servlet>
    <servlet-name>PasswordServlet</servlet-name>
    <servlet-class>com.stuff.PasswordServlet</servlet-class> 
</servlet>

<servlet-mapping>
    <servlet-name>PasswordServlet</servlet-name>
    <url-pattern>/PasswordServlet</url-pattern>
</servlet-mapping>

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>


</web-app>

Here is the corresponding bean that is to receive the value which is injected by the .

package com.stuff;

import javax.annotation.Resource;


/**
*
* @author me
*/

public class PasswordSessionBean {

@Resource() private String password;


    public String getPassword(){
        return password;
    }

}

Solution

  • If you instantiate the bean yourself you will not benefit from container services like dependency injection.

    In your case where you have a servlet and want to inject the env-entry into a dependent POJO, simply let the container inject the POJO into your servlet. So instead of calling new PasswordSessionBean() yourself add this to your servlet:

    @Inject
    private PasswordSessionBean passwordSessionBean;
    ...
    public void doGet(....) {
        assertEquals(passwordSessionBean.getPassword(), "SteveJobbs");
    }
    

    Defining the PasswordSessionBean is also a valid alternative, but seems to be an overkill for just getting an env-entry injected.