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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Pradeesh P
Guest
Pradeesh P

Hi,
I have a doubt. I got the same error message when I try to access the jsp page directly. From the following valuable comments I got that we have to call the jsp page through the action class inorder to populate the list. But how can we do that? I am totally confused with this issue. PLease help.

MK
Guest
MK

how to make button in front of s:select as it makes it own row and td so how can I show button in same row

sujata
Guest
sujata

need to write this ” select Acc Type, ACC_CODE,
DESCRIPTION FROM SR_DOC_INFO sd,
SR_ACC_CODE sa WHERE
sd.Acc Type = sa.ACC_CODE;” in my struts jsp page

Keya
Guest
Keya

Very helpful example. Thanks much MK Yong!

Gagana
Guest
Gagana
I am using struts2 framework in my work. I have some s:select tags in JSP, for which the values are populated from Database. I have 5 JSPs in a process. I select some option in a dropdown in a page and go to next page. This selected option is stored in a session. When I click back from next page to the previous page, the selected option is fetched from the session variable. In my select tag generated for that s:select in JSP, that particular option’s is selected attribute is set to “selected” when i inspect in the browser. But… Read more »
Gagana
Guest
Gagana

Hello Mr. Mkyong, I have some issues in struts2 application s:select tag. Could you please help me out??

juan
Guest
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();… Read more »
Ahmed
Guest
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)… Read more »
Anand
Guest
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
Guest
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
Guest
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
Guest
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
Guest
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)

Harshad
Guest
Harshad

Can you pls share the code of web.xml and calling action?

Muthu
Guest
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
Guest
Shailesh Bohra

Is there any way to create listboxes in struts 2

sakthivel
Guest
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
Guest
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
Guest
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
Guest
beginer

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

Joe
Guest
Joe

Obviously he didn’t test it. There’s some good information on his site, but I find a lot of untested garbage as well. Which just makes your job even that much more difficult in trying to understand your issue.

Nazia
Guest
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
Guest
Anuj

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

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

Anuj
Guest
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
Guest
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
Guest
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
Guest
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… Read more »
TAPAS CHANDRA BASKEY
Guest
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
Guest
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?

gulam samdani
Guest
gulam samdani

how to integreate Struts2 with Jquery ?
pls give idea ?

trackback
Request for Struts2+Hibernate3 Sample project - Lazydesis

[…] I found this tutorial: click here let me know if this helps […]

alkeshtech
Guest
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?

trackback
Struts 2 <s:doubleselect> example

[…] is refer to the second drop down list. The data population is same with the “<s:select>” […]

trackback
Struts 2 <s:combobox> combo box example

[…] down list into the generated text box automatically. To create a drop down list , you should use <s:select> tag […]