November 22, 2014
Hot Topics:

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

  • February 3, 2011
  • By Leonard Anghel
  • Send Email »
  • More Articles »

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).

Tags: JSF, JSP, CDI

Originally published on http://www.developer.com.


Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel