How to use <h:selectOneMenu /> tag JSF 2.0 Example


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

First create a managed bean by using the annotation syntax;

package generator;

import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.model.SelectItem;

/**
 *
 * @author tunatore
 */
@ManagedBean(name=”generator”)
@RequestScoped
public class OptionSelectGenerator {

private List<SelectItem> options = null;
    /** Creates a new instance of OptionSelectGenerator */
private String selected;
public OptionSelectGenerator() {
this.selected = “SelectItemValue1”;
options = new ArrayList<SelectItem>();
SelectItem item1 = new SelectItem(“SelectItemValue1”, “SelectItemLabel1”);
SelectItem item2 = new SelectItem(“SelectItemValue2”, “SelectItemLabel2”);
SelectItem item3 = new SelectItem(“SelectItemValue3”, “SelectItemLabel3”);
SelectItem item4 = new SelectItem(“SelectItemValue4”, “SelectItemLabel4”);
options.add(item1);
options.add(item2);
options.add(item3);
options.add(item4);
}
  public List<SelectItem>  getOptions() {
return options;
}

/**
     * @param options the options to set
     */
public void setOptions(List<SelectItem> options) {
this.options = options;
}

/**
     * @return the selected
     */
public String getSelected() {
return selected;
}

    /**
     * @param selected the selected to set
     */
public void setSelected(String selected) {
this.selected = selected;
}
}

Use it inside xhtml file

<?xml version=’1.0′ encoding=’UTF-8′ ?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml&#8221;
xmlns:h=”http://java.sun.com/jsf/html&#8221;
xmlns:f=”http://java.sun.com/jsf/core”&gt;
<h:head>
<title>h:selectOneMenu example</title>
</h:head>
<h:body style=”background-color: aquamarine”>
<h:form>
<h1><h:selectOneMenu/>  example</h1>
        <h:selectOneMenu value=”#{generator.selected}” onchange=”submit();”>
            <f:selectItems value=”#{generator.options}” />
       </h:selectOneMenu>
<b>Selected –></b> <b><h:outputText value=”#{generator.selected}”/></b>
</h:form>
</h:body>
</html>

Sample output;


Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s