Question

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>
Was it helpful?

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

OTHER TIPS

You don't mention which servlet container/application server and which CDI implementation version you're using.

I have no clue what Spring Tool Suite assumes as default, presumably it's Tomcat, Spring and no CDI at all, so you have to add and configure a CDI implementation (e.g. Weld or OpenWebBeans).

For CDI 1.0, you'll have to add a WEB-INF/beans.xml descriptor (which may be empty) to have your beans discovered. This is no longer necesary for CDI 1.1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top