JavaJava Tip: Use EL Names to Access a Bean from Non-Java Code

Java Tip: Use EL Names to Access a Bean from Non-Java Code

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

You can reference a bean in non-Java code as long as the code supports unified expression language (EL) expressions. All you need to do is assign the bean an EL name. After you do that, the bean will be accessible from JSP and JSF pages, or any other context capable of understanding EL expressions.

You use the @Named annotation to indicate the EL name. This following annotation demonstrates this by calling a bean from non-Java code:

package com.mybeans;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class MyBean {

    private String email = "myemail@yahoo.com";

    //this is a business logic method
    public void checkEmail() {   //...   }
    }

    //getter and setter methods for email property
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Thanks to the @Named annotation, you can access the bean properties and business logic methods from a JSF page like this:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 
      xmlns_h="http://java.sun.com/jsf/html">
    <h:head>
        <title>Call a CDI bean</title>
    </h:head>
    <h:body>
        <h:form id="myForm">
            <p><h:outputLabel value="Press the button to call the bussines method ..."/></p>
            <p><h:commandButton value="Call checkEmail" action="#{myBean.checkEmail}"/></p>
            <p><h:outputText value="#{myBean.email}"/></p>
        </h:form>
    </h:body>
</html>

Without the @Named annotation, this bean is invisible to the JSF page.

Author Notes:

  1. You can also specify the bean name to be used, like this:
    @Named("bean_name")
  2. Do not forget that an application that uses CDI must have a file named beans.xml (it can be empty, but it MUST be present).

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories