Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get managed bean name from inside the backing bean?

Tags:

jsf

I'm using JSF 1.1. I have the following in my faces-config.xml file:

<managed-bean>
    <managed-bean-name>beanInstance1</managed-bean-name>
    <managed-bean-class>com.paquete.BeanMyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

I want get the managed bean name beanInstance1 inside my bean. This is my bean:

package com.paquete;

public class BeanMyBean {
   String atribute1;

   public BeanMyBean () {
       System.out.println("managed-bean-class="+this.getClass().getName());
       System.out.println("managed-bean-name="+????????????????????????);
       // How Can I get the "beanInstance1" literal from here??
   }

   // setters and getters
}

I know how get the com.paquete.BeanMyBean literal (this.getClass().getName()) and the BeanMyBean (this.getClass().getSimpleName()), but I don't know how get a Managed Name (instance of Bean).

How can I get the beanInstance1 value?

like image 227
John Avatar asked Oct 10 '22 03:10

John


1 Answers

This information is not available by the standard JSF API. Best what you can get is to walk through all the request, session and application scopes yourself the following way (code is copied from this blog):

public static String lookupManagedBeanName(Object bean) {
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, Object> requestMap = externalContext.getRequestMap();

    for (String key : requestMap.keySet()) {
        if (bean.equals(requestMap.get(key))) {
            return key;
        }
    }

    Map<String, Object> sessionMap = externalContext.getSessionMap();
    for (String key : sessionMap.keySet()) {
        if (bean.equals(sessionMap.get(key))) {
            return key;
        }
    }

    Map<String, Object> applicationMap = externalContext.getApplicationMap();
    for (String key : applicationMap.keySet()) {
        if (bean.equals(applicationMap.get(key))) {
            return key;
        }
    }

    return null;
}

However, there's a big but, this doesn't work inside the bean's constructor simply because JSF hasn't placed it in any scope yet! You need to determine it at a later point, e.g. in an action method.

public void submit() {
    String name = lookupManagedBeanName(this);
    // ...
}

Unrelated to the concrete problem, this is a design smell. The concrete functional requirement for which you thought that this is the solution has definitely to be solved differently.

like image 65
BalusC Avatar answered Jan 01 '23 10:01

BalusC