如何使用Post-Redirect-Get with Spring MVC将对象传递给GET处理程序?

时间:2012-01-20 21:42:09

标签: spring-mvc post-redirect-get

我是Spring MVC的新手,并试图让Post / Redirect / Get模式正常工作。我们正在尝试实施一项调查,其中每个页面都可以显示可变数量的问题。我想要实现它的方式是一个GET处理程序,它准备下一个调查页面,然后将其交给视图。在同一个Controller中,有一个Post处理程序,用于处理表单对调查问题的答案,将其提交给调查服务,调查服务返回下一页问题,然后将下一个surveyPage重定向到getNextPage GET处理程序。

其中大部分都有效,但问题是我不知道如何将“下一个调查页面”对象从POST处理程序传递到重定向中的getNextPage GET处理程序。重定向正在运行;它从POST方法转到GET方法,但surveyPage ModelAttribute是GET方法中的新对象,而不是在POST方法结束时设置的对象。如您所见,我已尝试使用ModelAttribute,但它不起作用。我也尝试在类上面使用@SessionAttributes,但后来得到了一个HttpSessionRequiredException。

我们不知道如何使用Spring MVC Forms处理包含变量问题的动态表单,所以我们只是直接使用JSTL。这很时髦但它确实有效。这种funkiness导致使用@RequestBody和SurveyPageBean返回Post。老实说,我不知道如何填充SurveyPageBean。它看起来像一些Spring MVC魔术,但它正在工作,所以我暂时不管它(另一个开发人员做了这个,然后我把它拿起来,我们都是Spring MVC的新手)。请不要被异常的表单处理分心,除非这是空的surveyPage ModelAttribute没有被重定向的问题的一部分。

这是Controller代码段:

@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";       
    }

2 个答案:

答案 0 :(得分:2)

使用Flash 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";
}

答案 1 :(得分:0)

您的GET将surveyPage作为模型属性,这意味着它正在从URL中读取它。在POST中,不是将surveyPage添加到模型中(因为您告诉客户端重定向而丢失,这会创建新请求,因此创建新模型),您应该将surveyPage作为查询参数添加到{{1你必须看看如何从查询参数构造surveyPage,以便知道在查询字符串上放什么。

例如,如果SurveyPage是根据用户,页码和问题计数等构建的,我相信您可以执行"redirect:surveyPage"之类的操作,以便传递该模型属性。