我使用以下代码创建了一个自定义JSF组件:
@FacesComponent("MainMenu")
public class MenuComponent extends UIComponentBase {
private List<MenuItem> items;
private String title;
public MenuComponent() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<MenuItem> getItems() {
return items;
}
public void setItems(List<MenuItem> items) {
this.items = items;
}
public String getFamily() {
return UI.FAMILY;
}
}
然后我为组件添加了一个渲染器:
@FacesRenderer(componentFamily = UI.FAMILY, rendererType = "MainMenuRenderer")
public class MenuComponentRenderer extends Renderer {
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
MenuComponent menuComponent = (MenuComponent) component;
ResponseWriter responseWriter = context.getResponseWriter();
responseWriter.startElement("ul", menuComponent);
responseWriter.writeAttribute("class", "sidebar-menu", "");
// заголовок
responseWriter.startElement("li", menuComponent);
responseWriter.writeAttribute("class", "header", "");
responseWriter.write(menuComponent.getTitle());
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
MenuComponent menuComponent = (MenuComponent) component;
ResponseWriter responseWriter = context.getResponseWriter();
responseWriter.endElement("ul");
// title
responseWriter.endElement("li");
// menu items
for (MenuItem menuItem : menuComponent.getItems()) {
responseWriter.startElement("li", menuComponent);
}
}
}
然后在taglib.xml中注册了组件:
<tag>
<tag-name>mainMenu</tag-name>
<component>
<component-type>MainMenu</component-type>
<renderer-type>MainMenuRenderer</renderer-type>
</component>
<attribute>
<name>items</name>
<required>true</required>
</attribute>
<attribute>
<name>title</name>
<required>true</required>
</attribute>
</tag>
在JSF页面中,我以下列方式使用它:
<mds:mainMenu items="${sidebar.menuItems}" title="Главное меню"</mds:mainMenu>
标签与侧边栏托管bean相关,bean尽可能简单:
@ManagedBean(name = "sidebar", eager = true)
@RequestScoped
public class Sidebar {
@Inject
private MenuService menuService;
private List<MenuItem> menuItems;
public Sidebar() {
System.out.println("Hello, world!");
}
@PostConstruct
public void init(){
setMenuItems(menuService.getMainMenu());
}
public List<MenuItem> getMenuItems() {
return menuItems;
}
public void setMenuItems(List<MenuItem> menuItems) {
this.menuItems = menuItems;
}
}
但是!我在渲染器中具有“title”属性的值,但不是“items”!如何将“items”属性值传递给我的组件?当我调试时,没有调用“Sidebar”bean。我的代码出了什么问题?
答案 0 :(得分:0)
Object value = menuComponent.getValueExpression(“items”)。getValue(context.getELContext());