【问题标题】:redirect with model object in spring在春季使用模型对象重定向
【发布时间】:2014-02-20 11:00:17
【问题描述】:

我需要将一个对象传递到我要重定向的页面中

@RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
    public ModelAndView createNewQuest(Quest quest,ModelAndView mav) {
        questService.addQuest(quest);


        mav.addObject("quest", quest);
        mav.setViewName("redirect:/control/displayQuest");
        return mav;
    }

我的控制器类看起来像这样,但是 displayQuest 页面没有得到任务对象?

任何帮助将不胜感激..

【问题讨论】:

  • 您正在寻找 FlashAttribute see
  • 你能把你的重定向控制器放在这里吗?

标签: java spring jsp


【解决方案1】:

Spring 添加了Flash Attributes 来处理这种情况:

带注释的控制器通常不需要使用 FlashMap 直接地。相反,@RequestMapping 方法可以接受一个参数 键入 RedirectAttributes 并使用它为 重定向场景。通过 RedirectAttributes 添加的 Flash 属性是 自动传播到“输出”FlashMap。同样在之后 自动添加来自“输入”FlashMap 的重定向属性 到为目标 URL 提供服务的控制器的模型。

示例

    @RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
    public ModelAndView createNewQuest(@ModelAttribute("quest") Quest quest,
         BindingResult binding, ModelAndView mav, 
             final RedirectAttributes redirectAttributes) {

        questService.addQuest(quest);

        redirectAttributes.addFlashAttribute("quest", quest);
        mav.setViewName("redirect:/control/displayQuest");
        return mav;
    }

【讨论】:

  • 它显示 HTTP 状态 500 - 请求处理失败;嵌套异常是 org.springframework.web.bind.annotation.support.HandlerMethodInvocationException:无法调用处理程序方法 [public org.springframework.web.servlet.ModelAndView com.quest.controller.QuestController.createNewQuest(com.quest.model.dto .Quest,org.springframework.web.servlet.ModelAndView,org.springframework.web.servlet.mvc.support.RedirectAttributes)];
  • 它以前工作过吗?我觉得有趣的是@ModelAttribute 没有放在Quest 之前。
  • 是的,在此之前已经磨损了,但没有设置对象是问题
  • 所以Quest 没有从某种形式进行数据绑定?
  • 它是如何被数据绑定的?
【解决方案2】:

如果您使用的是 spring 表单标签,那么您的表单标签应该如下所示

<form:form name="yourformname" id="formid" commandName="quest">

然后你的控制器模型对象“quest”将被映射到spring表单标签commandName变量,稍后你可以访问该变量

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多