0

I was reading this entire introduction to understand when and why we should choose a specific Scope, it is clear for static fields and methods, but for the objects of the Bean itself it is not, at least for me.

Bean1:

@ManagedBean
@SessionScoped
public class ConsultBean   implements java.io.Serializable {
    public  String name="oldName";
    
    public String getResults(){
    return "index";  
    }
    ..
      

Bean2:

@ManagedBean
@SessionScoped
public class TestBean   implements java.io.Serializable {
    public  ConsultBean obj=new ConsultBean();
    
     public String show(){
     obj.setName("newName");
     return obj.getResults(); 
    }
    ..

index.jspx/xhtml

<h:panelGrid  columns="2">
<h:outputText value="Result:"/>
<h:outputText value="#{consultBean.name}"/> 
</h:panelGrid>

The result was: oldName!

But when:

public String getResults(){
    this.setName("New Name")
    return "index";  
    }

The result is STILL: oldName!!

Does the object where the call initiated matter?

Community
  • 1
  • 1
EngTiyeb
  • 38
  • 8
  • I'm no JSF expert, but are you certain `show()` and `getResult()` are called? Because these methods seem to be the only place where the name can be changed. Also `show()` will never change anything as it's changing the name of `ConsultBean` created in `TestBean` itself. So it's a new object that isn't the same as the one used by JSF – Stijn Van Bever Nov 27 '18 at 15:41
  • Thank you @StijnVanBever, So JSF uses one object of the class an keep it, the rest are "Copies"! the scope is also meant only for that object? – EngTiyeb Nov 27 '18 at 15:47
  • If you do `new ConsultBean();` you don't create a managed bean saying this instace is not managed by JSF at all. On the other hand EL-Expressions like `#{consultBean.something}` do refer to the JSF managed bean. If you want `ConsultBean` to be injected to `TestBean.obj`, you'll have to annotate it with `@ManagedProperty`, so JSF would set `obj` to the JSF managed `ConsultBean` instance. – Selaron Nov 27 '18 at 15:57

1 Answers1

2

The problem is public ConsultBean obj=new ConsultBean();, you are not supposed to instantiate managed beans. It's the job of the framework to do it for you, that's the whole point of managed beans.

Inject ConsultBean with ManagedProperty.

Although, I would suggest you to use CDI instead of the old jsf bean api

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24