How to get a managed bean name from inside a bean?

I am using JSF 1.1. In my file faces-config.xml, I have the following:

<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 to get a managed bean name beanInstance1inside 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 to get the literal com.paquete.BeanMyBean( this.getClass().getName()) and BeanMyBean( this.getClass().getSimpleName()), but I don't know how to get the managed name (Bean instance).

How can I get the value beanInstance1?

+5
source share
1 answer

This information is not available in the standard JSF API. The best you can get is to go through all the queries, sessions and applications yourself as follows (the 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;
}

, , bean , JSF - ! , . .

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

, . , , , -.

+4

All Articles