我使用spring mvc创建了一个非常简单的测验应用程序。它工作正常。但是现在,如果用户遇到第三个问题,而另一个浏览器(另一个用户)发出另一个请求,则会向第三个用户提出第四个问题。我不希望发生这种情况。每个新的请求都应该从第一个问题开始测验。如何在不为每个用户提供登录表单的情况下实现这一目标,并将来自不同浏览器的每个新请求标识为不同的用户?我知道这可以通过会话来实现。春季MVC中的Http会话
有人可以解释如何做到这一点?
package dmv2.spring.controller;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import dmv2.form.QuestionForm;
import dmv2.model.Exam;
import dmv2.model.Question;
@Controller
@SessionAttributes
@RequestMapping("/Exam")
public class ExamController
{
private List<Question> questions = (new Exam()).getQuestions();
private int index = 0;
private int score = 0;
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showQuestionForm()
{
Question q = questions.get(index);
return new ModelAndView("exam", "questionForm", new QuestionForm()).addObject("q", q);
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView showQuestionForm2(@ModelAttribute("questionForm") QuestionForm questionForm, BindingResult result)
{
Question q = questions.get(index);
if(q.getAnswer().getRightChoiceIndex() == Integer.parseInt(questionForm.getChoice()))
score = score + 1;
index = index + 1;
if(index < questions.size())
{
q = questions.get(index);
}
else
return new ModelAndView("result").addObject("score", score);
return new ModelAndView("exam", "questionForm", new QuestionForm()).addObject("q", q);
}
}
很好的答案!感谢您的回答。我自动编写了@Scope(“session”),它为每个不同的会话创建了不同的状态,并且一切正常。你是否还建议我创建一个类或接口来存储状态,就像你所做的那样,而不是将整个控制器连接到一个会话范围内?是的,我了解将业务逻辑远离控制器的重要性。这只是一个旨在了解spring mvc的简单应用程序。 – SerotoninChase