【发布时间】:2016-08-27 11:14:01
【问题描述】:
我的问题如下。
我想用 JSF 做一个问卷调查,我想在页面上增加一个计数器。最好的方法可能是同时设置一个 ajax 事件。
这里是 index.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Test</title>
</h:head>
<h:body>
Question :
<h:form id="questionForm">
<h:outputLabel value="#{questionBean.questions[0].askedQuestion}">
</h:outputLabel>
<h:selectOneRadio>
<f:selectItems value="#{questionBean.questions[0].proposals}"
var="proposal" itemValue="#{proposal}" />
</h:selectOneRadio>
</h:form>
</h:body>
</html>
如您所见,第一个问题的值是创建的列表的第一个元素。我想设置一个计数器,以便在每次点击时解决 n+1 个问题。
这里是问题豆:
package trainforjava.question;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
@Controller
public class QuestionBean {
static Logger log = Logger.getLogger(QuestionBean.class.getName());
private List<Question> questions;
private int counter = 0;
public QuestionBean() {
QuestionCreator creator = new QuestionCreator();
questions = creator.createQuestions();
System.out.println(questions);
Collections.shuffle(questions);
System.out.println(questions);
log.info(questions);
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public int increment() {
counter++;
return counter;
}
}
我想将方法 increment() 称为页面的参数,然后在整个问卷中递增。我尝试使用,但它仅用于支持 bean。
有人可以帮助我吗?
谢谢你
【问题讨论】:
-
您有多种选择。最简单的一种可能是对整个问卷使用单个 bean,并根据计数器参数值渲染具体部分。如果您仍想使用不同的视图,您可以将计数器值作为request parameter 甚至parameter in the flash scope 传递。其他解决方案是将其存储在会话中,但如果用户打算在不同的浏览器选项卡中工作,则不建议这样做。
-
顺便问一下,你是如何管理你的豆子的?您为此使用Spring吗?如果您使用 Spring 的
@Controller注释而没有声明范围,则 bean 将是单例(应用程序范围)。 -
谢谢。我发布了我如何实现它。我不知道它是否真的经过优化,但这是一个建议: