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

Thursday Feb 3rd 2011 by Leonard Anghel
Share:

If you use non-Java code that supports unified expression language, you can use it to make any CDI bean accessible to JSP or JSF.

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="http://www.w3.org/1999/xhtml"
      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).
Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved