Struts <html:select> drop down box example

Download this Struts select option (drop down box) example – Struts-Select-Option-Example.zip

In this Struts example, you will learn how to create a HTML select option (drop down box) with Struts <html:select> and <html:option> tag. The <select> tag is used to create a select list (drop-down list); while <option> tags inside the select element define the available options in the list.

1. Folder Structure

This is the final project structure created by Maven. Please create the corresponding folders.

Struts-select-option-folder

2. Action class

Create an Action class, do nothing but forward the request.

HtmlSelectOptionAction.java


package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HtmlSelectOptionForm;

public class HtmlSelectOptionAction extends Action{
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) 
        throws Exception {
		
	  HtmlSelectOptionForm htmlSelectOptionForm = (HtmlSelectOptionForm)form;
		
	  return mapping.findForward("success");
	}
	
}

3. Properties file

Create a properties file, and declare the error and label messages.

Common.properties


#error message
error.common.html.select.required = Please select a year.

#label message
label.common.html.select.name = Select a year 
label.common.html.select.button.submit = Submit
label.common.html.select.button.reset = Reset

4. ActionForm

Create a ActionForm, contains a year variable to hold the select option value.

HtmlSelectOptionForm.java


package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HtmlSelectOptionForm extends ActionForm{
	
	String year;

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	  HttpServletRequest request) {
		
	    ActionErrors errors = new ActionErrors();
	      
	    if( getYear() == null || ("".equals(getYear())))
	    {
	       errors.add("common.select.err",
	    	 new ActionMessage("error.common.html.select.required"));
	    }
	      
	    return errors;
	}
	
	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		year = "";
	}

}

5. JSP Page

Use the Struts’s HTML tag <html:select> and <html:option> to create a HTML drop down list.

select.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>





Struts html:select example

: -- None -- 1980 1981 1982 1983 1984 1985

Get the selected drop down box value from htmlSelectOptionForm form and display it

display.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>





Your selected year is :

6. struts-config.xml

Create a Struts configuration file and link all together.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="htmlSelectOptionForm"
			type="com.mkyong.common.form.HtmlSelectOptionForm"/>
	
	</form-beans>

	<action-mappings>
	
	        <action
			path="/SelectPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/select.jsp"/>
	
		<action
			path="/Select"
			type="com.mkyong.common.action.HtmlSelectOptionAction"
			name="htmlSelectOptionForm"
			validate="true"
			input="/pages/select.jsp"
			>	
			
			<forward name="success" path="/pages/display.jsp"/>
		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config>

7. web.xml

Final step, create a web.xml and integrate the Struts framework.


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Maven Struts Examples</display-name>
  
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
    
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app>

Access it

http://localhost:8080/StrutsExample/SelectPage.do

Struts-select-option-example1

Select a year and pressed the submit button, it will forward to

http://localhost:8080/StrutsExample/Select.do

and display the selected drop down box value.

Struts-select-option-example2

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
kannan smart
Guest
kannan smart

How can i add dynamically option and value in tag and how can i get value in tag.

am added dynamically value and option in html;select tag. but hoe to get value from this tag.

i get below error:

javax.servlet.ServletException: javax.servlet.jsp.JspException: Cannot find bean: “namelist” in any scope

goods
Guest
goods

I am only commenting to let you know what a outstanding encounter my friend’s child encountered reading yuor web blog. She learned some things, which included what it’s like to have a very effective teaching nature to get many people without hassle have an understanding of selected tortuous matters. You undoubtedly exceeded our expectations. Many thanks for coming up with these good, safe, informative as well as easy guidance on the topic to Tanya.

sankar
Guest
sankar
in struts 1.3.10 ,i want to display value in dropdrop list from database. DAO class return a list object , how to display arraylist object in jsp. Action class: masterList = UploadDAO.getValues(“list”); request.setAttribute(“masterlist”, masterList); Dao Class : Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection(); UploadVO uVO = null; logger.debug(“in DAO query is ” + SQLQueries.GET_POLICY_MASTER); stmt = conn.prepareStatement(SQLQueries.GET_POLICY_MASTER); masterList = new ArrayList(); rs = stmt.executeQuery(); while (rs.next()) { uVO = new UploadVO(); uVO.setmId(rs.getString(1)); uVO.setmValue(rs.getString(2)); masterList.add(uVO); logger.debug(“added do ” + uVO); } } catch (Exception exp) { logger.error(“Exception is ” +… Read more »
chinkun
Guest
chinkun

in the above drop-down-box-example you hard-code the value.But i want to brought it from database not hard-code.can you kindly give me the code?

sankar
Guest
sankar

please help me how to set the values in dropdown list from database , with in jsp page how to get the array list values in dropdown list ?

kannan smart
Guest
kannan smart
Hi Sankar, i solve that problem…….. dealer_bean.java: //getter and setter method public String getCustomername() { return customername; } public void setCustomername(String customername) { this.customername = customername; } public ArrayList getCustomerList() { ArrayList customer_list = new ArrayList(); /*Create Session Factory Object*/ SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); Query enc_password = session.createQuery(“from account_dao”); List list = enc_password.list(); for (Iterator iterator = list.iterator(); iterator.hasNext();) { account_dao account = (account_dao) iterator.next(); System.out.println(“Id : ” + account.getId()); System.out.println(“Account Name : ” + account.getName()); System.out.println(“Account Password : ” + account.getPassword()); customer_list.add(account.getName()); } return customer_list; } public void setCustomerList(ArrayList customerList) { this.customerList = customerList;… Read more »
trackback
Struts <html:select> drop down box example | Struts - html

[…] wi?cej: Struts <html:select> drop down box example | Struts Tags: drop-down, html, learn-how, select-option, struts-, you-will Comments RSS […]