Get JSF managed bean by name in any Servlet related class

前端 未结 6 647
难免孤独
难免孤独 2020-11-22 01:33

I\'m trying to write a custom servlet (for AJAX/JSON) in which I would like to reference my @ManagedBeans by name. I\'m hoping to map:

http://host

6条回答
  •  遥遥无期
    2020-11-22 01:45

    I use this:

    public static  T getBean(Class clazz) {
        try {
            String beanName = getBeanName(clazz);
            FacesContext facesContext = FacesContext.getCurrentInstance();
            return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
        //return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
        } catch (Exception ex) {
            return null;
        }
    }
    
    public static  String getBeanName(Class clazz) {
        ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
        String beanName = managedBean.name();
    
        if (StringHelper.isNullOrEmpty(beanName)) {
            beanName = clazz.getSimpleName();
            beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
        }
    
        return beanName;
    }
    

    And then call:

    MyManageBean bean = getBean(MyManageBean.class);
    

    This way you can refactor your code and track usages without problems.

提交回复
热议问题