我是Spring MVC的新手,正在尝试使用Post/Redirect/Get模式。我们正在尝试实现一个调查,其中每个页面可以显示不同数量的问题。我想要实现的方式是一个GET处理程序,它准备下一个调查页面,然后将其传递给视图。在同一个控制器中,有一个处理表单对调查问题的回答的Post处理程序,将其提交给调查服务,调查服务返回下一页问题,然后将下一个surveyPage重定向到getNextPage GET处理程序。
除了问题是我不知道如何在重定向中将“下一个调查页”对象从POST处理程序传递到getNextPage GET处理程序之外,大部分都是有效的。重定向是有效的;它从POST方法转到GET方法,但surveyPage ModelAttribute是GET方法中的新对象,而不是在POST方法末尾设置的对象。如您所见,我尝试过使用ModelAttribute,但它不起作用。我也尝试在类的上面使用@SessionAttributes,但是得到了一个HttpSessionRequiredException。
我们不知道如何使用Spring MVC表单来处理包含变量#问题的动态表单,所以我们直接使用了JSTL。它很时髦,但它是有效的。这就是为什么使用@RequestBody和SurveyPageBean的原因。老实说,我不知道SurveyPageBean是如何填充的。它看起来像一些Spring MVC魔术,但它正在工作,所以我暂时不去管它(另一个开发人员做了这件事,然后我学会了它,我们都是Spring MVC的新手)。请不要被不寻常的表单处理分心,除非这是空的surveyPage ModelAttribute没有被重定向的问题的一部分。
下面是控制器的代码片段:
@Controller
@RequestMapping("/surveyPage")
public class SurveyPageController{
@RequestMapping(method=RequestMethod.GET)
public String getNextPage(@ModelAttribute("surveyPage") SurveyPage surveyPage, Model model) {
if(surveyPage.getPageId() == null) {
// call to surveyService (defined elsewhere) to start Survey and get first page
surveyPage = surveyService.startSurvey("New Survey");
}
model.addAttribute("surveyPage", surveyPage);
return "surveyPage";
}
@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@RequestBody String body, SurveyPageBean submitQuestionBean, Model model, @ModelAttribute("surveyPage") SurveyPage surveyPage) {
// process form results, package them up and send to service, which
// returns the next page, if any
surveyPage = surveyService.submitPage(SurveyPageWithAnswers);
if (results.getPageId() == null) {
// The survey is done
surveyPage = surveyService.quitSurvey(surveyId);
return "redirect:done";
}
model.addAttribute("surveyPage ", surveyPage );
return "redirect:surveyPage";
}发布于 2013-01-29 04:27:51
使用Warlock's Thoughts中所示的Flash属性。
@RequestMapping(method = RequestMethod.POST)
public String handleFormSubmission(..., final RedirectAttributes redirectAttrs) {
...
redirectAttrs.addFlashAttribute("AttributeName", value);
return "redirect:to_some_url_handled_by_BController";
}发布于 2012-01-21 06:16:46
GET将surveyPage作为模型属性,这意味着它将从URL中读取它。在本文中,您应该将surveyPage作为查询参数添加到"redirect:surveyPage"中,而不是将surveyPage添加到模型中(这会丢失,因为您告诉客户端重定向,从而创建新的请求,从而创建新的模型)。您必须查看surveyPage是如何从查询参数构造的,以便知道在查询字符串上放置什么内容。
例如,如果模型是由用户、页码和问题计数等构建的,我相信您可以执行类似"redirect:surveyPage?userId=1234&pageNumber=5678&questionCount=12的操作来传递surveyPage属性。
https://stackoverflow.com/questions/8948203
复制相似问题