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

  • 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

    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.

  • http://www.hitchitspl.com 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 ….

  • http://comment 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….

  • http://johanandersson.info 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?

    • http://johanandersson.info 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 :)

      • http://johanandersson.info Johan Andersson

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

        &lt;s:radio label=&quot;Answer&quot; name=&quot;yourAnswer&quot; list=&quot;#{true:'Yes',false:'No'}&quot; value=&quot;getDefaultAnswerForRadioButton()&quot; /&gt;
  • Elaine

    Hi mkyong,

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

    for example:

     &lt;s:radio id=&quot;groupBy&quot; value=&quot;1&quot; list=&quot;#{'1':'Month','2':'Day'}&quot; onclick=&quot;checkValue ()&quot;&gt;&lt;/s:radio&gt;

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

    Thanks.

    Elaine

    • 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

    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

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

      • tyler

        Hi,

        can you tell us what the problem was?

        Cheers

        Tyler

        • tyler

          I have the same problem!!!

          • 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

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

  • 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

    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

    Thanks a lot for providing this type of tutorials.

  • abhishek

    what are the jar files required.

    • http://www.mkyong.com mkyong

      This is Maven project, bro. the pom.xml file is included in the attachment zip file.

  • 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

    • http://www.mkyong.com mkyong

      I believe no one can answer by just view the statement above :). Zip your project and send it to me, Maven project prefer.

      P.S Do not send me all the included libraries, as it will caused my mail server goes down TT…

  • Pingback: How to preselect a radio button value in Struts 2()