Weld + JSF - strange behavior
vadger Feb 10, 2010 12:00 PMHello,
I'm a newbie in Weld and CDI. Can anybody explain the following behavior.
Here is my controller
@RequestScoped
//@Named
//@Stateless
@ManagedBean
public class MyBean implements Serializable {
public MyBean() {
System.err.println("**** MyBean constructor");
}
private String hello;
public void sayHello() {
System.err.println("*** sayHello: " + this.hello);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Goood..."));
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(this.hello));
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
System.err.println("***** HELLO: " + this.hello);
}
}
And view
<!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"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<f:view>
<h:form>
<div style="color: green">
<h:messages id="messages"/>
</div>
<h:inputText value="#{myBean.hello}"/>
<h:commandButton action="#{myBean.sayHello}" value="Click me"/>
</h:form>
</f:view>
</h:body>
</html>
When I'm using pure JSF loading the page I'm getting in console output:
SEVERE: **** MyBean constructor
Submitting the form:
SEVERE: **** MyBean constructor SEVERE: ***** HELLO: Hello, world SEVERE: *** sayHello: Hello, world
Quite logical.
If instead of @ManagedBean I'm using @Named annotation (of course adding beans.xml in WEB-INF) I'm getting quite strange behavior.
Loading the page
SEVERE: **** MyBean constructor
Submitting the form:
SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: ***** HELLO: Hello, world SEVERE: **** MyBean constructor SEVERE: *** sayHello: null SEVERE: **** MyBean constructor
The bean is created 4 times, then the setter is invoked, after that again the bean is created and sayHello method is invoked and lastly the bean again is created (redirect?).
If I add @Stateless annotation the behavior is changing a little (data is not lost)
Loading the page
SEVERE: **** MyBean constructor
Submitting the form:
SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: **** MyBean constructor SEVERE: ***** HELLO: Hello, world SEVERE: **** MyBean constructor SEVERE: *** sayHello: Hello, world SEVERE: **** MyBean constructor
Why is the bean too often created?
I'm using Glassfish v3 that comes with Netbeans 6.8.
Regards,
Vadim