Configure Managed Beans in JSF 2.0

In JSF 2.0, Java bean that can be accessed from JSF page is called Managed Bean. The managed bean can be a normal Java bean, which contains the getter and setter methods, business logic or even a backing bean (a bean contains all the HTML form value).

There are two ways to configure the managed bean :

1. Configure Managed Bean with Annotation

In JSF 2.0, you can annotated a Managed Bean with new @ManagedBean annotation.

package com.mkyong.common;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2. Configure Managed Bean with XML

With XML configuration, you can use the old JSF 1.x mechanism to define the managed bean in a normal faces-config.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
    <managed-bean>
      <managed-bean-name>helloBean</managed-bean-name>
      <managed-bean-class>com.mkyong.common.HelloBean</managed-bean-class>
      <managed-bean-scope>session</managed-bean-scope>
     </managed-bean>
</faces-config>

Best Practice

It’s recommended to put the managed beans in a separate XML file because the faces-config.xml is used to set the application level configurations.

So, you should create a new XML file and put the managed beans detail inside, and declared the XML file in the javax.faces.CONFIG_FILES initialize parameter, which is inside the WEB-INF/web.xml file.

web.xml

 ...
 <context-param>
    <param-name>javax.faces.CONFIG_FILES</param-name>
    <param-value>WEB-INF/manage-beans.xml</param-value>
  </context-param>
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值