Skip to content

How to put variable in OGNL tag

<input type="radio" name="${questions.qid}" value="${questions.ans1}" 
  <s:if test="%{('ans1')}">checked</s:if>>
<s:property value="#attr.questions.ans1"/>

In this code questions is a list which contain questions object with

String question,ans1,ans2,ans3;

In my program, I will make it appears in browser like

Question 1
(RadioButton) Answer 1
(RadioButton) Answer 2
(RadioButton) Answer 3

Question 2
(RadioButton) Answer 1
(RadioButton) Answer 2
(RadioButton) Answer 3


The list may contain multiple question objects so I made it to show 5 question per page. My problem is (for example) the user may go from page 4 to page 2 and I want to refill the answers the user have clicked in page 2. So in the action class, I create a HashMap and put question id (qid) and answered question (eg. ans2) into the map, then put this map into the session called map.

In above code, I use

<s:if test="%{('ans1')}">checked</s:if>

in the HTML radio tag. I hard coded the question id (qid) as 1 and it works as planned. But the number in the get() must be variable. That must be real question id like I used in


I tried put the parameter as

but it doesn’t work. How to make the parameter variable?


To populate your question you need to use the s:iterator tag.

<s:iterator value = "myQuestions" status="key">
  <s:textfield name = "myQuestions[%{#key.index}].name" /><br>
  <input type="radio" name="myQuestions[<s:property value="%{#key.index}"/>].ans1" value="<s:property value="%{myQuestions[#key.index].ans1}"/>" <s:if test="%{([#key.index].name)).equals(myQuestions[#key.index].ans1)}">checked</s:if>><s:property value="%{myQuestions[#key.index].ans1}"/><br>

in the action use map questions by name (equivalent your qid)

Map<String, String> map = new HashMap<String, String>();

the question class created from your description.

public class Question {
    private  String name;
    private  String ans1;
    private  String ans2;
    private  String ans3;

    //getters setters here

private List<Question> myQuestions;
//getters setters here for questions

make sure you initialize the questions before return result.

public String execute(){
  myQuestions = new ArrayList<Question>();
  myQuestions.add(new Question("Question1", "ans1", "ans2","ans3"));
  myQuestions.add(new Question("Question2","ans1", "ans2","ans3"));

  //test results, map should not be empty
  map.put("Question1", "ans1");
  map.put("Question2", "ans2");
  session.put("map", map);

In this example the first radio will be checked and second unchecked due to the session map values.

The input elements of the form are bound to the action by their names. If you need to get values when you submit the form you need to use indexed property names.