Search code examples
jsfcdimanaged-beannamed

How to form @Named Backing Bean in JSF


I read somewhere that it's better to use CDI @Named instead of JSF @ManagedBean, because of CDI, so I'm trying to convert some of my code. I'm trying to use @Named in JSF, but it's always unreachable. When using @ManagedBean there was no problem.

I'm using it like @ManagedBean, as below

CustomerBacking.java

package com.wordpress.marczykm.backing;

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

@Named("customer")
@RequestScoped
public class CustomerBacking {

    @EJB
    private CustomerService customerService;

    public CustomerBacking() {
    }

    public String addCustomer(Customer customer) {
        customerService.addCustomer(customer);
        return "customer_overview";
    }

    public Customer getCustomer(){
        return customerService.getCustomer();
    }
}

index.xhtml

    <!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:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core">

    <h:head>
        <title>EJB 3.0 Test</title>
    </h:head>
    <h:body>
        <h:outputText value="#{customer.firstname}"/>
        <h:form>
            <h:outputText value="Imię"/>
            <h:inputText id="firstname" name="firstname" value="#{customer.firstname}" /><br/>

            <h:outputText value="Nazwisko"/>
            <h:inputText id="lastname" name="lastname" value="#{customer.lastname}" /><br/>

            <h:commandButton value="Dodaj" actionListener="#{customer.addCustomer}"/>
        </h:form>
</h:body>
</html>

Solution

  • To sum up, looking at Netbeans sample CDI app, the bean which needs to be accesible by JSF page needs to:

    • have @Named annotation (javax.inject.Named)
    • have scope annotation (like @SessionScoped, @RequestScoped, @ViewScoped), but imported from javax.enterprise.context.*
    • doesn't have to have empty, non-argument constructor
    • and the thing that wasn't in my code is that, that the bean needs to implement Serializable (java.io.Serializable)
    • last thing is that if your app is a web application it needs a beans.xml (can be completly empty) in WEB-INF directory, if it is a bean app it have to be in META-INF directory