Struts 2 <s:radio> radio button example

In Struts 2 , you can use the <s:radio> tag to create a HTML radio button. The funny stuff is there are many ways to populate the data into the radio button, via List, OGNL or Object. Check the below example to know how.

Struts 2 <s:radio> example

Example to show the use of List, OGNL and Object to populate data to a radio button that’s created via Struts 2 <s:radio> tag.

1. Action

Action class to create list of the genders and languages values for radio button.

RadioButtonAction.java


package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import com.mkyong.common.model.Language;
import com.opensymphony.xwork2.ActionSupport;

public class RadioButtonAction extends ActionSupport{

	private List<String> genders;
	private List<Language> languages ;
	
	private String yourGender;
	private String yourAnswer;
	private String yourLanguage;
	
	private static final String MALE = "male";
	private static final String FEMALE = "female";
	private static final String UNKNOWN = "unknown";
	
	public RadioButtonAction(){
		
		genders = new ArrayList<String>();
		genders.add(MALE);
		genders.add(FEMALE);
		genders.add(UNKNOWN);
		
		languages = new ArrayList<Language>();
		languages.add( new Language("EN", "English") );
		languages.add( new Language("FR", "France") );
		languages.add( new Language("CN_ZH", "Chinese") );
		languages.add( new Language("DE", "German") );
		
	}
	
	//return default gender value
	public String getDefaultGenderValue(){
		return UNKNOWN;
	}

	//return default language value
	public String getDefaultLanguageValue(){
		return "CN_ZH";
	}
	
	public String execute() {
		return SUCCESS;
	}
	public String display() {
		return NONE;
	}
	
	//getter ad setter methods
}

Language.java


package com.mkyong.common.model;

public class Language{

	private String languageCode;
	private String languageDisplay;
	
	//getter and setter methods
	
	public Language(String languageCode, String languageDisplay) {
		this.languageCode = languageCode;
		this.languageDisplay = languageDisplay;
	}
}

2. Result page

Result page to use Struts 2 “s:radio” to create three radio buttons via List, OGNL and object.

radiobutton.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 radio button example</h1>

<s:form action="resultAction" namespace="/">

<h2>
  <s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
  <s:radio label="Gender" name="yourLanguage" list="languages" 
      listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
  <s:radio label="Answer" name="yourAnswer" list="#{'1':'Yes','2':'No'}" value="2" />
</h2> 

<s:submit value="submit" name="submit" />
	
</s:form>

</body>
</html>a

result.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 radio button example</h1>

<h2>
  Your Selected Gender : <s:property value="yourGender"/>
</h2> 
<h2>
  Your Selected Language : <s:property value="yourLanguage"/>
</h2> 
<h2>
  Your Selected Answer : <s:property value="yourAnswer"/>
</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="" namespace="/" extends="struts-default">
		
    <action name="radioButtonAction" 
         class="com.mkyong.common.action.RadioButtonAction" method="display">
		<result name="none">pages/radiobutton.jsp</result>
    </action>
		
    <action name="resultAction" class="com.mkyong.common.action.RadioButtonAction">
		<result name="success">pages/result.jsp</result>
    </action>
  </package>
	
</struts>

5. Demo

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

Struts2 radio button screen

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

Struts2 radio button screen
To understand how to preselect a value, read this article – preselect a radio button value in Struts 2

Reference

  1. http://struts.apache.org/2.0.11.2/docs/radio.html
  2. http://struts.apache.org/2.1.8.1/docs/struts-2-form-tags.html
  3. How to preselect a radio button value in Struts 2

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
bala
Guest
bala

type Exception report

message tag ‘radio’, field ‘list’, name ‘yourGender’: The requested list key ‘genders’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location] <—- i was getting this error when i run the project what should i do to make it run……

hu kevin
Guest
hu kevin

I try this program 2 days. To resolve this problem you can get from next example.
In result page, tag, the list=”genders” will call the getGenders() method to return a list of the keys and values for the radio button.

Binh Thanh Nguyen
Guest
Binh Thanh Nguyen

Thanks, nice post

Paru
Guest
Paru
Hi Mkyong, Thanks for posting these useful examples on Struts tags. I have been progressing just fine until I also encountered the same exception as posted by many for s:radio tag example. “The requested list key could not be resolved as a collection/array/map/enumeration/iterator type error in struts2” When I accessed the genders list by creating an instance of the action class I found that it is populated with the desired values – MALE,FEMALE etc. Also I had created setters/getters for genders – I am unable to fix this. Anyone who found the solution pls do suggest any tips towards resolving… Read more »
Rajkumar
Guest
Rajkumar

Hi Mkyong,

i am getting exception like

“SEVERE: Servlet.service() for servlet jsp threw exception
tag
‘radio’, field ‘list’, name ‘careerForm.gendeCd’: The requested list
key ‘genderCdList’ could not be resolved as a
collection/array/map/enumeration/iterator type. Example: people or
people.{name} – [unknown location]”

Could you please advice me to get out of this issue…

Paru
Guest
Paru

am facing the same problem – cud u pls share the solution if u resolved this?
Thanks!

Paru
Guest
Paru
Solved this problem with a hint provided in another forum : We are facing this problem because when the jsp page is loaded initially, the list is not populated.(The list gets populated only after you submit the page and control gets routed to action class) .So to avoid this, create an index page which routes to the action class as follows: // this will only run the action class to populate the list first. In struts.xml make the following changes : struts.xml ———— /radiobutton.jsp /error.jsp /result.jsp Flow will be : index—-> actionclass—–>radiobuttonjsp—->result.jsp
Alexander
Guest
Alexander

I noticed that if you want to set default value, but you don’t want to create a new field in action, you can do like that:

Paru
Guest
Paru

thanks for this tip!

Sunita
Guest
Sunita

Hi Mkyong,
I want to know regarding radio button in Struts 2.
1) On clicking of one radio , two radio buttons should display.
2) On clicking of one radio , one textfield should display.

So which nd how the tags should I use??

Thanks in Advance.

Harish
Guest
Harish

Hi,
Thanks for your examples.
I have a question. Is it possible to display list of values in vertical way along with checkbox and radio button.

sneha
Guest
sneha

Hi sir very nice tutorial … could u plz tell how to place the radio buttons one below the other using themes and templates. could u plz post a sample code for this ….

swetha
Guest
swetha

Hi
i have tried the radio button example same as above but i am not able to execute it. i am getting the below error on typing the url in the myeclipse web browser…

org.apache.jasper.JasperException: Error on line 25, column 9 in template/simple/radiomap.ftl
stack.findValue(parameters.listKey) is undefined.
It cannot be assigned to itemKey – Class: freemarker.core.Assignment
File: Assignment.java
Method: accept
Line: 111 – freemarker/core/Assignment.java:111:-1
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:159)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)

root cause

Could you please help me on this…i am using myeclipse with struts2 and maven dependencies….

Johan Andersson
Guest
Johan Andersson

Great tutorial! Is it possible to get a boolean value out of the selected radiobutton instead of integers 1 and 2, and make that preselected?

Johan Andersson
Guest
Johan Andersson

I got it to work myself :) Here is how I did if any Struts-beginners like me are reading this:

I wanted the default answer to be NO, so I created a method in the action-class called getDefaultAnswerForRadioButton() that returns false. Maybe other solutions are possible but this worked :)

Johan Andersson
Guest
Johan Andersson

My comment got cut off, maybe because I use IE. Here is the code:

<s:radio label="Answer" name="yourAnswer" list="#{true:'Yes',false:'No'}" value="getDefaultAnswerForRadioButton()" />
Elaine
Guest
Elaine

Hi mkyong,

I would like to ask how to get the radio button once onclick.

for example:

 <s:radio id="groupBy" value="1" list="#{'1':'Month','2':'Day'}" onclick="checkValue ()"></s:radio> 

May i know how to get the value selected in the checkValue function?

Thanks.

Elaine

hemantha kumar
Guest
hemantha kumar

it is simple if u think, just u hv to make sure that u should execute the action class, when u onclick the radio button, this can be achieved through ajax call….

sampath
Guest
sampath

i tried above code but im getting exception saying

Struts Problem Report
Struts has detected an unhandled exception:

Messages: tag ‘radio’, field ‘list’, name ‘yourGender’: The requested list key ‘genders’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name}
tag ‘radio’, field ‘list’, name ‘yourGender’: The requested list key ‘genders’ could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} – [unknown location]

File: org/apache/jasper/servlet/JspServletWrapper.java
Line number: 541

sampath
Guest
sampath

at last i got it……. thank you for tutorials….

tyler
Guest
tyler

Hi,

can you tell us what the problem was?

Cheers

Tyler

tyler
Guest
tyler

I have the same problem!!!

Vinod
Guest
Vinod

If you see in tutorial following link is called first
http://localhost:8080/Struts2Example/radioButtonAction.action

where list is populated with the values and this list is used in the jsp page to display the radio button options.

If you try to access jsp directly it gives the error message as it does not find any list.

Neel
Guest
Neel

in struts.xml….action name=”radioButtonAction”..frm where dis “radioButtonAction” is called ?

Huy
Guest
Huy

Dear MKyong!

How can get value key of list Language ?
Exampe: i want to get value key of English is “EN” or get value key of France is “FR”

Thank so much

Shaswat
Guest
Shaswat

Hi,

I don’t understand the flow of the above program of radio button, i mean how the values get displayed in radiobutton.jsp before calling the RadioButtonAction and when the constructor of action is called..

Pavan
Guest
Pavan

Thanks a lot for providing this type of tutorials.

abhishek
Guest
abhishek

what are the jar files required.

rad
Guest
rad

Hi,
Thanks for your example of how to use radio button.
I have few other text fields in the jsp, and I am using action-validation.xml to validate those text fields.
Upon validation error, directed to jsp.
Now jsp cant find list and throwing errors.
Can you help me to solve this problem.

Thanks and appreciate your help

trackback
How to preselect a radio button value in Struts 2

[…] Create a radio button in Struts 2 VN:F [1.9.1_1087]please wait…Rating: 0.0/10 (0 votes cast) […]