This article was last updated on : November 4th, 2016 at 8:37 am

JSF 1.2 Select One Menu (h:selectOneMenu) example

Tutorial JSF (1.2) – Select One Menu in JSF with example

1. In this tutorial will explain you how to work with Select One Menu component in JSF.
2. Select One Menu is one of very useful component in JSF. It is used often. For example Suppose We have a list of profession (Doctor, Engineer, Teacher, Public Service, Others) and user has to select one profession from that list then we will use component in JSF to display the list values. Select One menu () allows only one value to select.
3. We have these files while doing this example.

  1.  optionPage.jsp
  2.  displaySelectOneMenuExample.jsp
  3.  SelectOneMenuTestManagedBean.java
  4.  SelectOneMenuView.java
  5.  faces-config.xml
  6.  web.xml

4. Eclipse image for this project.

image <h:selectOneMenu> in JSF Eclipse Hierarchy
Eclipse Project Image for Select One Menu Example in JSF

Procedures to do this Example :

1. Creating a dynamic web application :
While writing this tutorial we are considering that you has basic knowledge of “Creating a Dynamic Project in JSF”. In this step we have to create a dynamic web application with name “SelectOneMenuInJSF” in eclipse. This dynamic web application should have JSF capabilities.
Please read this tutorial this tutorial – First Sample Hello World Example in JSF . This tutorial will explain you how to create first JSF web project in Eclipse using Apache Tomcat Server.
After creating JSF  dynamic Web Application, Let us see Select One Menu () in JSF.

2. Create JSP Pages :
Now we have to create two JSP pages.
1. optionPage.jsp – This is  page is options page. In this page user will be given options to select any one of them. We will validate the empty fields. If user will leave any field empty we will show one alert message saying that field is empty and please select value for this field.
2. displaySelectOneMenuExample.jsp – This page is for showing the values selected by user.

optionPage.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>h:selectOneMenu in JSF</title>
<script type="text/javascript">
    function validateFormValues() {
        var titleId = document.getElementById("selectOneMenuJSFTestFormID:titleId");
        var userNameId = document.getElementById("selectOneMenuJSFTestFormID:userNameId");
        var ageGroupId = document.getElementById("selectOneMenuJSFTestFormID:ageGroupId");
        var technologiesId = document.getElementById("selectOneMenuJSFTestFormID:technologiesId");
        var hobbiesId = document.getElementById("selectOneMenuJSFTestFormID:hobbiesId");
        var numberOffamiliyMembersId = document.getElementById("selectOneMenuJSFTestFormID:numberOFFamiliesId");
        if (titleId != null && titleId.value == '00') {
            alert("Please Select Your Title");
            return false;
        }
        if (userNameId != null && userNameId.value == '') {
            alert("Please Enter Your Name");
            return false;
        }
        if (ageGroupId != null && ageGroupId.value == '00') {
            alert("Please Select Your Age Group");
            return false;
        }
        if (technologiesId != null && technologiesId.value == '00') {
            alert("Please Select Your Working Technologies");
            return false;
        }
        if (hobbiesId != null && hobbiesId.value == '00') {
            alert("Please Select Your Hobby");
            return false;
        }
        if (numberOffamiliyMembersId != null && numberOffamiliyMembersId.value == '00') {
            alert("Please Number of Your Family Members");
            return false;
        }
        return true;
    }
</script>
</head>
<body>
    <f:view>
        <h:form id="selectOneMenuJSFTestFormID" onsubmit="return validateFormValues()">
            <h:panelGrid border="0" cellpadding="2" cellspacing="2" columns="2">
                <h:outputText value="Title :"></h:outputText>
                <h:selectOneMenu id="titleId" value="#{selectOneMenuTestMBean.viewModel.title}">
                    <f:selectItems value="#{selectOneMenuTestMBean.viewModel.titleOptions}" />
                </h:selectOneMenu>
                <h:outputText value="Your Good Name :"></h:outputText>
                <h:inputText id="userNameId"  value="#{selectOneMenuTestMBean.viewModel.yourName}"></h:inputText>
                <h:outputText value="Age Group :"></h:outputText>
                <h:selectOneMenu id="ageGroupId" value="#{selectOneMenuTestMBean.viewModel.ageGroup}">
                    <f:selectItems value="#{selectOneMenuTestMBean.viewModel.ageGroupOptions}" />
                </h:selectOneMenu>
                <h:outputText value="Technology You are working :"></h:outputText>
                <h:selectOneMenu id="technologiesId" value="#{selectOneMenuTestMBean.viewModel.technologies}">
                    <f:selectItems value="#{selectOneMenuTestMBean.technologiesOptions}" />
                </h:selectOneMenu>
                <h:outputText value="Hobby :"></h:outputText>
                <h:selectOneMenu id="hobbiesId" value="#{selectOneMenuTestMBean.viewModel.hobbies}">
                    <f:selectItem itemLabel="--Select--" itemValue="00" />
                    <f:selectItem itemLabel="Cricket" itemValue="Cricket" />
                    <f:selectItem itemLabel="Movies" itemValue="Movies" />
                    <f:selectItem itemLabel="Net Surfing" itemValue="Net Surfing" />
                    <f:selectItem itemLabel="Football" itemValue="Football" />
                    <f:selectItem itemLabel="Badminton" itemValue="Badminton" />
                    <f:selectItem itemLabel="Volleyball" itemValue="Volleyball" />
                </h:selectOneMenu>
                <h:outputText value="Total Family Members :"></h:outputText>
                <h:selectOneMenu id="numberOFFamiliesId" value="#{selectOneMenuTestMBean.viewModel.numberOffamiliyMembers}">
                    <f:selectItems value="#{selectOneMenuTestMBean.viewModel.numberOffamiliyMembersOptions}" />
                </h:selectOneMenu>
            </h:panelGrid>
            <h:panelGroup style="text-align:center;">
                <h:commandButton value="Display Selected Values" id="displayCMD"
                    action="showSelectedValues"></h:commandButton>
            </h:panelGroup>
        </h:form>
    </f:view>
</body>
</html>

displaySelectOneMenuExample.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>h:selectOneMenu in JSF</title>
</head>
<body>
    <f:view>
        <h:panelGrid border="0" cellpadding="2" cellspacing="2" columns="2">
            <h:outputText value="Title :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.title}"></h:outputText>
            <h:outputText value="Your Good Name :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.yourName}"></h:outputText>
            <h:outputText value="Age Group :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.ageGroup}"></h:outputText>
            <h:outputText value="Technology You are working :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.technologies}"></h:outputText>
            <h:outputText value="Hobby :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.hobbies}"></h:outputText>
            <h:outputText value="Total Family Members :"></h:outputText>
            <h:outputText style="font-family:arial;color:red;font-size:24px;" value="#{selectOneMenuTestMBean.viewModel.numberOffamiliyMembers}"></h:outputText>
        </h:panelGrid>
    </f:view>
</body>
</html>

3. Create Managed Bean For this Example :
Throughout this JSF example you can see value attributes like “#{selectOneMenuTestMBean.viewModel.hobbies}”

Here
selectOneMenuTestMBean – Manged Bean(SelectOneMenuTestManagedBean.java)
viewModel – View Model (SelectOneMenuView.java – Used to get & set values of the form field attribute)
hobbies – one attribute in SelectOneMenuView.java

selectOneMenuTestMBean will be defined in faces-config.xml file. Please see faces-config.xml file for this example.
Below code is for Managed Bean SelectOneMenuTestManagedBean.java .

SelectOneMenuTestManagedBean.java


package com.sitenol.selectOneMenu;
import java.util.Set;
import javax.faces.model.SelectItem;
public class SelectOneMenuTestManagedBean {
    private static final long serialVersionUID = 1L;
    public SelectOneMenuTestManagedBean(){
        viewModel = new SelectOneMenuView();
    }
    private SelectOneMenuView viewModel;
    public SelectOneMenuView getViewModel() {
        return viewModel;
    }
    public void setViewModel(SelectOneMenuView viewModel) {
        this.viewModel = viewModel;
    }
    public Set<SelectItem> getTechnologiesOptions() {
        return this.viewModel.getTechnologiesOptions();
    }
    public String displaySelectOneMenuValues(){
        return "showSelectedValues";
    }
}

4. Create View Model For this Example :
Inside Managed Bean SelectOneMenuTestManagedBean.java you can see
private SelectOneMenuView viewModel;
SelectOneMenuView.java is view model. Below given code is for  SelectOneMenuView.java

SelectOneMenuView.java


package com.sitenol.JSFFormValidation;
public class SelectOneMenuView {
    private String userName;
    private String technologiesYouWork;
    private String yourCompanyName;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getTechnologiesYouWork() {
        return technologiesYouWork;
    }
    public void setTechnologiesYouWork(String technologiesYouWork) {
        this.technologiesYouWork = technologiesYouWork;
    }
    public String getYourCompanyName() {
        return yourCompanyName;
    }
    public void setYourCompanyName(String yourCompanyName) {
        this.yourCompanyName = yourCompanyName;
    }
}

 

5. Create faces-config.xml file :
Please find the faces-config.xml file code here. This faces-config.xml file is for example using in JSF.

Faces-config.xml

<?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_1_2.xsd"

    version="1.2">

    <managed-bean>

        <managed-bean-name>selectOneMenuTestMBean</managed-bean-name>

        <managed-bean-class>com.sitenol.selectOneMenu.SelectOneMenuTestManagedBean</managed-bean-class>

        <managed-bean-scope>session</managed-bean-scope>

    </managed-bean>

    <navigation-rule>

        <display-name>Options Page</display-name>

        <from-view-id>/optionPage.jsp</from-view-id>

        <navigation-case>

            <from-outcome>showSelectedValues</from-outcome>

            <to-view-id>/displaySelectOneMenuExample.jsp</to-view-id>

        </navigation-case>

    </navigation-rule>

</faces-config>

6. Create web.xml file :
Please find the web.xml file code here. This web.xml file is for example using in JSF.

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>SelectOneMenuInJSF</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

    <servlet-name>Faces Servlet</servlet-name>

    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>Faces Servlet</servlet-name>

    <url-pattern>*.faces</url-pattern>

  </servlet-mapping>

  <context-param>

    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>

    <param-value>resources.application</param-value>

  </context-param>

  <context-param>

    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>

    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>

    <param-value>server</param-value>

  </context-param>

  <context-param>

    <description>

    This parameter tells MyFaces if javascript code should be allowed in

    the rendered HTML output.

    If javascript is allowed, command_link anchors will have javascript code

    that submits the corresponding form.

    If javascript is not allowed, the state saving info and nested parameters

    will be added as url parameters.

    Default is 'true'</description>

    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>

    <param-value>true</param-value>

  </context-param>

  <context-param>

    <description>

    If true, rendered HTML code will be formatted, so that it is 'human-readable'

    i.e. additional line separators and whitespace will be written, that do not

    influence the HTML code.

    Default is 'true'</description>

    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>

    <param-value>true</param-value>

  </context-param>

  <context-param>

    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>

    <param-value>false</param-value>

  </context-param>

  <context-param>

    <description>

    If true, a javascript function will be rendered that is able to restore the

    former vertical scroll on every request. Convenient feature if you have pages

    with long lists and you do not want the browser page to always jump to the top

    if you trigger a link or button action that stays on the same page.

    Default is 'false'

</description>

    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>

    <param-value>true</param-value>

  </context-param>

  <listener>

    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>

  </listener>

</web-app>

7. Deploy War file and Run Server :
In this step you we have to deploy SelectOneMenuInJSF.war  file to server after proper deployment we have to start the server.

8. Run The Application :
After successfully war deployment. Please start the server. After that open Internet Explorer and hit this “http://localhost:8080/SelectOneMenuInJSF/optionPage.faces”
So now we can see output of our  example in JSF.
Out put screen will be like this.

First Screen
Image showing out of Select One Menu Example in JSF
Output Page Where user can select single/one option

In the above screen you have to enter
1. Title :
2. Your Good Name :
3. Age Group :
4. Technology You are working :
5. Hobby :
6. Total Family Members :
We are validating these fields at client side using Java Script. If you will fail to enter any of these fields you will receive one alert message. When you will enter all the fields completely you will receive  Second Screen.

Second Screen
Image showing final out screen displaying values selected in Select One Menu in previous step.
Screen showing values selected by user

Share this post:

Recent Posts

One Comment

  1. Avatar for Tarun Singh
    Peter says:

    This is very interesting, You’re a very skilled blogger.
    I’ve joined your feed and look forward to seeking more
    of your wonderful post. Also, I’ve shared your site
    in my social networks!

Leave a Comment