2013-04-27 62 views
1
<input type="radio" name="${questions.qid}" value="${questions.ans1}" <s:if test="%{(#session.map.get(1)).equals(\'ans1\')}">checked</s:if>><s:property value="#attr.questions.ans1"/> 

在此代码中,“questions”是一个包含问题对象的列表,其中包含String question,ans1,ans2,ans3。在我的计划,我会让它出现在浏览器,如如何将变量放入OGNL标记

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

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

. 
. 
. 

列表中可能包含多个问题对象,因此我把它每页显示5的问题。我的问题是(例如)用户可从4页转到第2页,我想补充的用户点击了第2页所以在动作类的答案,我创建了一个HashMap,把问题ID(QID)和在地图中回答问题(例如ans2),然后将该地图放入名为“地图”的会话中。

在上面的代码中,我在HTML无线标签使用

<s:if test="%{(#session.map.get(1)).equals(\'ans1\')}">checked</s:if> 

。我将问题ID(qid)硬编码为“1”,并按计划运行。 但get()中的数字必须是可变的。那一定是真正的问题ID就像我在

name="$(questions.qid)" 

使用我试图把参数作为

#session.map.get(#attr.questions.qid) 

,但它不工作。请引导我如何使参数变量。

回答

1

要填充您的问题,您需要使用iterator标记。

<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="%{(#session.map.get(myQuestions[#key.index].name)).equals(myQuestions[#key.index].ans1)}">checked</s:if>><s:property value="%{myQuestions[#key.index].ans1}"/><br> 
</s:iterator> 
在操作使用地图问题

的名字(相当于你qid

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

从你的描述产生的问题类。

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 

确保您在返回结果前初始化问题。

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

在这个例子中,第一个无线电将被检查,第二个无线电由于会话映射值而被选中。

形式的输入元件被结合到由它们的名称的动作。如果您在提交表单时需要获取值,则需要使用索引属性名称。