【问题标题】:creating dynamic selectOneRadion using a bean使用 bean 创建动态 selectOneRadion
【发布时间】:2014-01-14 12:31:24
【问题描述】:

我需要构建一个包含问题的测验应用程序(每个问题有 2 个可能的答案)我在数据库中存储了一些问题。选择答案并单击“下一步”后,您将看到下一个问题。 我有一个代表每个问题的 bean,它被称为 Item,并且具有以下属性: 问题,ansA,ansB; 我有一个豆子:

@ManagedBean
@ViewScoped
public class Bean {

private List<Item> items = new ArrayList<Item>();
private List<Item> helper = new ArrayList<Item>();
private String myValue;
int indexHelp = 0;

public String next() {
    items.clear();
    items.add(helper.get(indexHelp));
    indexHelp++;

    System.out.println("chose: " + myValue);

    return "ok";
}

列表助手已与数据库中的问题一起存储

jsf 文件:

<h:form>
        <h:dataTable value="#{bean.items}" var="item">
            <h:selectOneRadio value="#{bean.myValue}">
                <h:column>
                    <f:selectItem itemLabel="#{item.question}"      />
                </h:column>
                <h:column>
                    <f:selectItem itemValue="1" itemLabel="#{item.ansA}" />
                </h:column>
                <h:column>
                    <f:selectItem itemValue="2" itemLabel="#{item.ansB}" />
                </h:column>

            </h:selectOneRadio>
        </h:dataTable>
        <h:commandButton value="Next" action="#{bean.next}" />
    </h:form>

问题是当我运行项目时,它没有显示单选按钮、问题或答案。 谢谢!!

【问题讨论】:

  • 好吧,我以为我知道你想要什么,但你的描述和你的代码矛盾。你说你只想显示一个问题,那你为什么要遍历一个列表呢?

标签: java jsf javabeans selectoneradio


【解决方案1】:

以下内容符合您的描述:

public class Item {
     String question;
     String chosen;
     String ansA;
     String ansB;
}

@ManagedBean
@ViewScoped
public AnswerBean implements Serializable {
     private List<Item> alreadyAnswered = new ArrayList<>();
     private Item nextQuestion;

     @PostConstruct
     public void retrieveNextQuestion() {
         // pull "next" question from DB and assign it to nextQuestion
     }

     public void save() {
         alreadyAnswered.add(nextQuestion);
         retrieveNextQuestion();
     }
}

你的 JSF 页面是这样的:

<h:form>
    <h:outputText value="#{answerBean.nextQuestion.question}" />
    <h:selectOneRadio value="#{answerBean.nextQuestion.chosen}">
        <f:selectItem itemValue="1" itemLabel"#{answerBean.nextQuestion.ansA}" />
        <f:selectItem itemValue="2" itemLabel"#{answerBean.nextQuestion.ansB}" />
    </h:selectOneRadio>
    <h:commandButton action="#{answerBean.save}" value="Next" />
</h:form>

您可能希望添加一个“评估”按钮,当没有问题或其他问题时显示该按钮(因为您需要对alreadyAnswered 问题列表某事)。

【讨论】:

  • 效果很好!但是当我运行它并选择一个答案并按下 Next 时,下一个问题的答案与我在前一个问题中选择的答案相同。你知道如何清除单选按钮(点击下一步之后)?
  • @user3168286 selectOneRadio 将显示匹配 nextQuestion.chosen 的值。在您致电save() 之后,请确保是null
猜你喜欢
  • 2017-11-19
  • 2012-06-04
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多