简体   繁体   中英

Javascript Variable Value Get From ManagedBean Property

I have a ManagedBean with a property which gets its value from an EJB. In the JSF, I have a Javascript variable which then gets its value from the ManagedBean property. When I run the project, the Javascript variable is not set.

In the ManagedBean, I tried the below methods but doesn't work:

  • setting the property's value in the Constructor

  • setting the property's value in an init() method with the @PostConstruct annotation

  • setting it in the getMenuData() method.

JSF JavaScript

<script>
    YAHOO.util.Event.onDOMReady(function ()) {
        // Data to build the menubar
        var menuData = [#{userMenu.menuData}];

        ...
    });
</script>

ManagedBean

package com.qrra.PROFIT.web;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import qrcom.profit.ejb.UserMenuFacade;

@ManagedBean
@ViewScoped
public class UserMenuController {

    public UserMenuController() {
        menuData = usermenu.buildMenuDataByUserProfile("UAT");
    }

    // @PostConstruct
    // public void init() {
    //    menuData = usermenu.buildMenuDataByUserProfile("UAT");
    // }

    public void getMenuData() {
        return this.menuData;
    }

    public void setMenuData(String menuData) {
        // usermenu.buildMenuDataByUserProfile("UAT");
        this.menuData = menuData;
    }

    private String menuData;
    @EJB
    private UserMenuFacade usermenu;

}

When I view source, I only see var menuData = [];

Is there a workaround to this?

The constructor approach would fail because it's impossible to inject an EJB in the instance before the instance is constructed, you'd only face a NullPointerException as the EJB is null . The @PostConstruct approach should work fine. The business-logic-in-getter approach will also work fine, but it is plain bad design .

Provided that you're properly preforming the job in the @PostConstruct , your code looks fine. Your concrete problem suggests that usermenu.buildMenuDataByUserProfile("UAT"); just returns an empty string by itself and thus your concrete problem needs to be solved at higher level. You should already have determined it by yourself with help of a debugger and common sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM