Struts 2 <s:select> drop down box example

In Struts 2 , you can use the <s:select> tag to create a HTML drop down box.

	<s:select label="What's your favor search engine" 
		headerKey="-1" headerValue="Select Search Engines"
		list="searchEngine" 
		name="yourSearchEngine" />

Resulting the following HTML code…

<td class="tdLabel">
   <label for="resultAction_yourSearchEngine" class="label">
       What's your favor search engine:
   </label>
</td> 
<td>
<select name="yourSearchEngine" id="resultAction_yourSearchEngine"> 
    <option value="-1">Select Search Engines</option> 
    <option value="google.com">google.com</option> 
    <option value="bing.com">bing.com</option> 
    <option value="yahoo.com">yahoo.com</option> 
    <option value="baidu.com">baidu.com</option> 
</select> 
</td>

The syntaxs are self explanatory, but the “headerKey” and “headerValue“. The “headerKey” is a key for the first item in the drop down list, and the “headerValue” is the value expression for the first item in the drop down list.

To auto select a default value for drop down box, read this artcle : Auto select drop down box value in Struts 2

Struts 2 <s:select> example

A full Struts 2 example to create drop down box via <s:select>, and populate the select options via Java list and OGNL list, stored the selected values and display it in another page.

1. Action

Action class to generate and hold the selected drop down box options.
SelectAction.java

package com.mkyong.common.action;
 
import java.util.ArrayList;
import java.util.List;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class SelectAction extends ActionSupport{
 
	private List<String> searchEngine;
 
	private String yourSearchEngine;
	private String yourMonth;
 
	public String getYourMonth() {
		return yourMonth;
	}
 
	public void setYourMonth(String yourMonth) {
		this.yourMonth = yourMonth;
	}
 
	public List<String> getSearchEngine() {
		return searchEngine;
	}
 
	public void setSearchEngine(List<String> searchEngine) {
		this.searchEngine = searchEngine;
	}
 
	public String getYourSearchEngine() {
		return yourSearchEngine;
	}
 
	public void setYourSearchEngine(String yourSearchEngine) {
		this.yourSearchEngine = yourSearchEngine;
	}
 
	public String getDefaultSearchEngine() {
		return "yahoo.com";
	}
 
	public SelectAction(){
 
		searchEngine = new ArrayList<String>();
		searchEngine.add("google.com");
		searchEngine.add("bing.com");
		searchEngine.add("yahoo.com");
		searchEngine.add("baidu.com");
	}
 
	public String execute() {
		return SUCCESS;
	}
 
	public String display() {
		return NONE;
	}
 
}

2. Result page

Render the drop down box via “<s:select>” tag, and populate the select options via Java list and OGNL list

select.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 drop down box example</h1>
 
<s:form action="resultAction" namespace="/">
 
<h2>
	<s:select label="What's your favor search engine" 
		headerKey="-1" headerValue="Select Search Engines"
		list="searchEngine" 
		name="yourSearchEngine" 
		value="defaultSearchEngine" />
</h2> 
 
<h2>
	<s:select label="Select a month" 
		headerKey="-1" headerValue="Select Month"
		list="#{'1':'Jan', '2':'Feb', '3':'Mar', '4':'Apr'}" 
		name="yourMonth" 
		value="2" />
</h2> 
 
<s:submit value="submit" name="submit" />
 
</s:form>
 
</body>
</html>

result.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
 
<body>
<h1>Struts 2 drop down box example</h1>
 
<h2>
  Favor search engine : <s:property value="yourSearchEngine"/>
</h2> 
 
<h2>
  Selected month : <s:property value="yourMonth"/>
</h2> 
 
</body>
</html>

3. struts.xml

Link all together ~

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 
 <constant name="struts.devMode" value="true" />
 
<package name="default" namespace="/" extends="struts-default">
 
   <action name="selectAction" 
         class="com.mkyong.common.action.SelectAction" method="display">
	<result name="none">pages/select.jsp</result>
   </action>
 
   <action name="resultAction" class="com.mkyong.common.action.SelectAction">
	<result name="success">pages/result.jsp</result>
   </action>
  </package>
 
</struts>

5. Demo

http://localhost:8080/Struts2Example/selectAction.action

Struts2 drop down box example

http://localhost:8080/Struts2Example/resultAction.action

Struts2 drop down box example

Reference

  1. Struts 2 select documentation
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: over here()

  • Pingback: over here()

  • Pingback: water ionizer()

  • Pingback: loan payment plan()

  • Pingback: water ionizer loans()

  • Pingback: pay per day loan plans()

  • Pingback: payment plan()

  • Pingback: ionizer payment plan()

  • Pingback: electricians burlington vt()

  • Pingback: house blue()

  • Pingback: alkaline water brands()

  • Pingback: alkaline water machine()

  • Pingback: laan penge nu uden renter()

  • Pingback: car parking()

  • Pingback: water ionizer machines()

  • Pingback: hurtigt laan penge nu()

  • Pingback: mobile porn()

  • Pingback: lan penge nu og her 18 ar()

  • Pingback: parking()

  • Pingback: check out DIRECTV channels()

  • Pingback: TVPackages.net()

  • Pingback: kangen water()

  • Pingback: kangen water()

  • Pingback: alkaline()

  • Pingback: water ionizer()

  • Pingback: tv online, online tv()

  • Pingback: watch free movies online()

  • Pingback: watch movies online free()

  • Pingback: streaming movies()

  • Pingback: Blue Coaster33()

  • juan

    buenas
    estos tratando de realizar un ejerccio con dos tablas producto y categoria
    con struts y hebernate

    el problema es cuando realizo el formulario de ingreso de productos donde esta el nombre precio cantidad y un select para tomar los datos de la tabla de categoria pero no doy no se cual es el error
    este es el error que me arroja

    SEVERE: Initial SessionFactory creation failed.org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: modelo.entity.Producto.idcategoria in modelo.entity.Categoria.productoLista

    esto es lo que tengo

    ProductoDoa

    @Override
    public List listaCategoria() {

    Listlistas=null;
    try{
    session=this.getSession();
    trans=session.beginTransaction();
    listas=session.createQuery(“from Categoria”).list();
    // Criteria criteria= session.createCriteria(Categoria.class);
    // listas=criteria.list();

    trans.commit();
    }catch(HibernateException e){
    e.printStackTrace();
    }finally{
    session.close();
    }
    return listas;
    }

    el control

    public String formulario()throws Exception{
    titulo=”Ingresar Producto”;
    if(id>0){
    producto=dao.busarporId(id);
    titulo=”Editar Producto”;

    }else{
    producto=new Producto();

    }

    return SUCCESS;

    }

    public String guardar()throws Exception {

    dao.guardar(producto);

    return SUCCESS;

    las tabla de Producto

    @Entity
    @Table (name=”producto”)
    public class Producto implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Column
    private String nombre;
    private int precio;
    private int cantidad;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name=”idcategoria”)
    private Categoria categoria;

    public Producto() {
    }

    public Producto(String nombre){
    this.nombre=nombre;

    }
    getersYSeter

    tablas de categoria

    @Entity
    @Table(name=”categoria”)
    public class Categoria implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int idcategoria;

    @Column
    private String descripcion;
    @OneToMany(mappedBy=”idcategoria”)
    public ListproductoLista=new ArrayList();
    public Categoria() {
    }

    public Categoria(String descripcion){
    this.descripcion=descripcion;
    }
    seterYgeters

    y el formulario

    y es te

  • Ahmed

    I am developing a web application with Struts2 and Hibernate / JPA and I’m stuck for two days I have 2 entities User and Role : Users can have one role and the role is attributed to several user and I wanted to feed a dropdown list from a database mysql in my JSP page the line of code are as following : thank you for helping

    @Entity
    @Table(name=”ROLE”)
    public class Role {

    private Long ROLE_ID;
    private String ROLE_NAME;
    private String ROLE_Description;

    private Set user;

    @Id
    @GeneratedValue
    @Column(name=”ROLE_ID”, length=100)
    public Long getROLE_ID() {
    return ROLE_ID;
    }
    public void setROLE_ID(Long ROLE_ID) {
    this.ROLE_ID = ROLE_ID;
    }

    @Column(name=”ROLE_NAME” ,length=100)
    public String getROLE_NAME() {
    return ROLE_NAME;
    }
    public void setROLE_NAME(String rOLE_NAME) {
    ROLE_NAME = rOLE_NAME;
    }

    @Column(name=”ROLE_DESCRIPTION” ,length=100)
    public String getROLE_Description() {
    return ROLE_Description;
    }
    public void setROLE_Description(String rOLE_Description) {
    ROLE_Description = rOLE_Description;
    }

    @OneToMany(cascade={CascadeType.ALL} ,mappedBy=”ROLE”)
    public Set getUser() {
    return user;
    }
    public void setUser(Set user) {
    this.user = user;
    }}

    ———————-Entities User ——————————-
    @Entity
    @Table(name=”USERS”)
    public class User {

    private Long USER_ID;
    private String USER_NAME;
    private String USER_PRENOM;
    private String USER_LOGIN;
    private String USER_PASSWORD;
    //private long ROLE_ID;
    private Role ROLE;

    @Id
    @GeneratedValue
    @Column(name=”USER_ID” ,length=100)
    public Long getUSER_ID() {
    return USER_ID;
    }
    public void setUSER_ID(Long uSER_ID) {
    USER_ID = uSER_ID;
    }

    @Column(name=”USER_NAME” ,length=100)
    public String getUSER_NAME() {
    return USER_NAME;
    }
    public void setUSER_NAME(String uSER_NAME) {
    USER_NAME = uSER_NAME;
    }

    @Column(name=”USER_PRENOM” ,length=100)
    public String getUSER_PRENOM() {
    return USER_PRENOM;
    }
    public void setUSER_PRENOM(String uSER_PRENOM) {
    USER_PRENOM = uSER_PRENOM;
    }

    @Column(name=”USER_LOGIN” ,length=100)
    public String getUSER_LOGIN() {
    return USER_LOGIN;
    }
    public void setUSER_LOGIN(String uSER_LOGIN) {
    USER_LOGIN = uSER_LOGIN;
    }

    @Column(name=”PASSWORD” ,length=100)
    public String getUSER_PASSWORD() {
    return USER_PASSWORD;
    }
    public void setUSER_PASSWORD(String uSER_PASSWORD) {
    USER_PASSWORD = uSER_PASSWORD;
    }

    @ManyToOne
    @JoinColumn(name=”ROLE_ID”)
    public Role getROLE() {
    return ROLE;
    }
    public void setROLE(Role rOLE) {
    ROLE = rOLE;
    }

    public User(String uSER_LOGIN, String uSER_PASSWORD) {
    super();
    USER_LOGIN = uSER_LOGIN;
    USER_PASSWORD = uSER_PASSWORD;
    }
    public User() {
    super();
    }
    }

    ———————-interface UsersDao ——————————-

    public interface UsersDao {

    public void saveOrUpdateUser(User user);
    public List listUser();
    public User listUserById(Long userId);
    public void deleteUser(Long userId);

    public List GetListRoleUser();
    }

    ———————-UserDaoImpl UsersDao ——————————-
    public class UserDaoImpl implements UsersDao {

    @SessionTarget
    Session session;

    @TransactionTarget
    Transaction transaction;

    /**
    * Used to list
    */
    @SuppressWarnings(“unchecked”)
    @Override
    public List GetListRoleUser() {
    List ListRoleDao = null;
    try {
    ListRoleDao = session.createQuery(“from Role”).list();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return ListRoleDao;
    }

    /**
    * Used to save or update a user.
    */
    @Override
    public void saveOrUpdateUser(User user) {
    try {
    session.saveOrUpdate(user);
    } catch (Exception e) {
    transaction.rollback();
    e.printStackTrace();
    }
    }
    }

    —————————UsersAction ——————————————-

    public class UsersAction extends ActionSupport implements ModelDriven{

    private static final long serialVersionUID = -6659925652584240539L;

    private User user=new User();
    private UsersDao userdao=new UserDaoImpl();
    private List userlist = new ArrayList();

    private List roleList = new ArrayList();
    private String role;

    public List getRoleList() {
    return roleList;
    }
    public void setRoleList(List roleList) {
    this.roleList = roleList;
    }
    public String getRole() {
    return role;
    }
    public void setRole(String role) {
    this.role = role;
    }

    @Override
    public User getModel() {
    return user;
    }

    /**
    * To save or update user.
    * @return String
    */
    public String saveOrUpdate(){

    userdao.saveOrUpdateUser(user);
    return SUCCESS;
    }

    /**
    * Getters/Setters
    */
    public User getUser() {
    return user;
    }
    public void setUser(User user) {
    this.user = user;
    }

    public UsersDao getUserdao() {
    return userdao;
    }
    public void setUserdao(UsersDao userdao) {
    this.userdao = userdao;
    }

    public List getUserlist() {
    return userlist;
    }
    public void setUserlist(List userlist) {
    this.userlist = userlist;
    }

    public static long getSerialversionuid() {
    return serialVersionUID;
    }

    }

    —————————file `struts.xml`——————————————-

    /manageUserr.jsp

    /manageUserr.jsp

    —————————file manageUserr.jsp——————————————-

    —————————error exception——————————————-

    SEVERE: Servlet.service() for servlet [jsp] in context with path [/Meditel] threw exception [tag ‘select’, field ‘list’, name ‘role': The requested list key ‘roleList’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location]] with root cause
    tag ‘select’, field ‘list’, name ‘role': The requested list key ‘roleList’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location]
    at org.apache.struts2.components.Component.fieldError(Component.java:240)
    at org.apache.struts2.components.Component.findValue(Component.java:333)

  • Anand

    Thanks for the blog. Is there any way that we can populate this with ajax call and then refresh a div where the drop down placed.
    If I get I will keep post that. Some one already tried please let me know.

  • megha jain

    how to implement dependable dropdown using struts2 i.e. on slection of first dropdown , second dropdown values get filled and dropdown values from mysql DB.

  • Elliott Waldrop

    This simply does not work. The “list” parameter is not filled from the List in the ActionSupport class. If you replace list=”searchEngine” with list=”{‘google.com’,’bing.com’,’yahoo.com’,’baidu.com’}” it works.

    • Elliott Waldrop

      ok, ok, ok, It does work. :\ BUT, you can’t call the select.jsp directly, like making it your welcome-file, ala web.xml. You must call it through an action, ala selectAction.action. If you make index.jsp your welcome-file and put:

      document.entryForm.submit();

      it should work.

      • Elliott Waldrop

        using parenthesis instead of angle brackets .jsp tags…

        (body)
        (s:form theme=”simple” name=”entryForm” action=”selectAction”)

        (/s:form)
        (/body)
        (script language=”javascript” type=”text/javascript”)
        document.entryForm.submit();
        (/script)

  • Muthu

    Hai Mr.mkyong, i want to know where i need to put the following code:

    What’s your favor search engine:

    Select Search Engines
    google.com
    bing.com
    yahoo.com
    baidu.com

    in this example? Pls help me!!! I’m stuck with this example.

  • Shailesh Bohra

    Is there any way to create listboxes in struts 2

  • sakthivel

    I tried your example but received the following error message. Did you not receive this when you tested it?

    org.apache.jasper.JasperException: tag ‘select’, field ‘list’, name ‘yourSearchEngine’: The requested list key ‘searchEngine’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location]

    • Nakul

      Dear Sakthivel,

      I am getting the same error. Did you find out the solution for this?
      I am using struts 2.3.4.1

      Regards,
      Nakul

      • Deraga

        use localhost:8080/Struts2Example/selectAction.action instead of localhost:8080/Struts2Example/pages/select.jsp

        because if we access the jsp file directly, we’re not going through the struts2 framework workflow and the Action Class would not be initialized when jsp file is rendering resulting jsp file not finding the List object as the error indicates.

        hope this helps :)

        • beginer

          I have the same error, dear mkyong how to fix it? I specify action in browser not jsp

  • Nazia

    Hiii,
    I want this functioning in Spring Framework MVC , I want a dropdown list in jsp which fetches the data from the data base,.,all i want is to showing data in dropdown list which is already stored in my database..

  • Anuj

    it seems the code i wrote in my previous comment is not being displayed.

    s:select list=”#{menuList,’All’}”

  • Anuj

    Hi,
    I want something like this.

    Here menuList will give me a list say Apple,Banana. I want to merge a option ‘All’ with this list from jsp page.

    When i write above code in jsp, it takes Apple,Banana as one option and All as second.
    I want Apple,Banana,All as 3 seperate options.

    Any suggestions?

  • Nandhini

    Hi Mkyong,

    Can you give me the solution for validating the struts2 drop down box using java script? I have tried many possible ways , but i could not figure it out.

    • Sarvendra Vikram Yadav

      try it may be solve your problem of drop down box using java script

      My Article

      function setOptions(chosen) {
      var selbox = document.myform.opttwo;

      selbox.options.length = 0;
      if (chosen == ” “) {
      selbox.options[selbox.options.length] = new Option(‘Please select above first’,’ ‘);

      }
      if (chosen == “1”) {
      selbox.options[selbox.options.length] = new
      Option(‘Cricket’,’oneone’);
      selbox.options[selbox.options.length] = new
      Option(‘FootBall’,’onetwo’);
      selbox.options[selbox.options.length] = new
      Option(‘Batminton’,’oneone’);
      selbox.options[selbox.options.length] = new
      Option(‘Chess’,’oneone’);
      }
      if (chosen == “2”) {
      selbox.options[selbox.options.length] = new
      Option(‘B.E./B.Tech’,’twoone’);
      selbox.options[selbox.options.length] = new
      Option(‘MCA’,’twotwo’);
      selbox.options[selbox.options.length] = new
      Option(‘MBA’,’twotwo’);
      selbox.options[selbox.options.length] = new
      Option(‘M.Tech’,’twotwo’);
      }
      if (chosen == “3”) {
      selbox.options[selbox.options.length] = new
      Option(‘Music’,’threeone’);
      selbox.options[selbox.options.length] = new
      Option(‘Movi’,’threetwo’);
      selbox.options[selbox.options.length] = new
      Option(‘Dance’,’threetwo’);
      selbox.options[selbox.options.length] = new
      Option(‘Play’,’threetwo’);
      }
      }

      Catgories

      Sports
      Education
      Entertainment

      Please select above first

  • Labeeb

    Dear Mkyong,

    I am a student who learn Struts 2.0. I know the Struts 1.3 very well. Now I am trying to develop my all Ideas through Struts 2.0. Here a problem with select box, I want to set value field and text field, both are different.

    Now I’m working with NetBeans IDE 7.1, so I don’t know how to run the downloaded source code. I’m also trying to do, this source code and my knowledge with NetBeans but a error is occur in web.xml.

    So I kindly request you to a step by step information to solve the both problems, like how to configure my PC, witch software are required and how to set values in select box.

  • TAPAS CHANDRA BASKEY

    Hi Alonzo !!! Check yr web.xml. It might have the welcome page or index.jsp mapped to it. Becoz It is not calling the action class. It is calling the jsp file directly.. :(

    • Pankaj Sinha

      Hi Tapas,

      Even m getting the same error what Alonzo is getting. The problem is the page where m got to use the select tag is my second page in the application i.e after the login page. So please walk me thru the structure of web.xml and struts.xml. i guess the web.xml will anyhow point to the login page. What should i do after the login is success?

  • http://www.optinfra.com gulam samdani

    how to integreate Struts2 with Jquery ?
    pls give idea ?

  • Pingback: Request for Struts2+Hibernate3 Sample project - Lazydesis()

  • alkeshtech

    Nice tutorials, I am using Struts2 jQuery 2.3.1 for one of my projects. How would you create 3 drop down menus where 3rd one depends on 2nd, and 2nd depends on the 1st one? Hints?

    • http://www.mkyong.com mkyong

      Struts 2 comes with a “doubleselect” component which can handle two drop down boxes automatically. Where the 2nd depends on the 1st, see
      http://www.mkyong.com/struts2/struts-2-sdoubleselect-example/

      If you really cant find a ready solution for 3 drop down boxes, then just do it manually.

      1. In Strust 2 , create 3 normal select components.
      2. In jQuery, attach event and set the value depend on the other drop down list, jQuery comes with powerful DOM traversing function, which should be quite easy, see below article to set the drop down box value in jQuery.

      http://www.mkyong.com/jquery/how-to-set-a-dropdown-box-value-in-jquery/

      • alkeshtech

        Yeah, but how can I call an action when 1st drop down is selected and pass its value as parameter? I m not sure how to do that.

        Thanks again.

        • http://www.mkyong.com mkyong

          Please reviewed doubleselect codes for hints, or you can use jQuery to call a ajax call to load the data dynamically.

          • Alonzo

            Mkyong,

            I tried your example but received the following error message. Did you not receive this when you tested it?

            org.apache.jasper.JasperException: tag ‘select’, field ‘list’, name ‘yourSearchEngine': The requested list key ‘searchEngine’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location]

  • Pingback: Struts 2 <s:doubleselect> example()

  • Pingback: Struts 2 <s:combobox> combo box example()