如何将模型属性从一个 Spring MVC 控制器传递到另一个控制器?

发布于 2024-12-05 06:13:28 字数 80 浏览 3 评论 0原文

我正在从一个控制器重定向到另一个控制器。但我还需要将模型属性传递给第二个控制器。

我不想让模型进入会话。

请帮忙。

I am redirecting from a controller to another controller. But I also need to pass model attributes to the second controller.

I don't want to put the model in session.

Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

我们的影子 2024-12-12 06:13:28

我使用 spring 3.2.3,这是我解决类似问题的方法。
1) 在控制器1的方法参数列表中添加RedirectAttributesredirectAttributes。

public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes)

2) 在方法内部添加代码,将flash属性添加到redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

3) 然后,在第二个控制器使用 @ModelAttribute 注释的方法参数来访问重定向属性

@ModelAttribute("mapping1Form") final Object mapping1FormObject

以下是来自控制器 1 的示例代码:

@RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes) {

    redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

    return "redirect:mapping2";
}   

来自控制器 2:

@RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model) {

    model.addAttribute("transformationForm", mapping1FormObject);

    return "new/view";  
}

I use spring 3.2.3 and here is how I solved similar problem.
1) Added RedirectAttributes redirectAttributes to the method parameter list in controller 1.

public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes)

2) Inside the method added code to add flash attribute to redirectAttributes redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

3) Then, in the second contoller use method parameter annotated with @ModelAttribute to access redirect Attributes

@ModelAttribute("mapping1Form") final Object mapping1FormObject

Here is the sample code from Controller 1:

@RequestMapping(value = { "/mapping1" }, method = RequestMethod.POST)
public String controlMapping1(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model, 
        final RedirectAttributes redirectAttributes) {

    redirectAttributes.addFlashAttribute("mapping1Form", mapping1FormObject);

    return "redirect:mapping2";
}   

From Contoller 2:

@RequestMapping(value = "/mapping2", method = RequestMethod.GET)
public String controlMapping2(
        @ModelAttribute("mapping1Form") final Object mapping1FormObject,
        final BindingResult mapping1BindingResult,
        final Model model) {

    model.addAttribute("transformationForm", mapping1FormObject);

    return "new/view";  
}
岁月打碎记忆 2024-12-12 06:13:28

仅使用redirectAttributes.addFlashAttribute(...) -> “redirect:...” 也有效,不必“重新插入”模型属性。

谢谢,阿博斯基!

Using just redirectAttributes.addFlashAttribute(...) -> "redirect:..." worked as well, didn't have to "reinsert" the model attribute.

Thanks, aborskiy!

雨巷深深 2024-12-12 06:13:28

我认为最优雅的方法是在 Spring MVC 中实现自定义 Flash Scope。

闪存范围的主要思想是存储来自一个控制器的数据,直到第二个控制器中的下一次重定向

请参阅我对自定义范围问题的回答:

Spring MVC 自定义作用域 bean

此代码中唯一缺少的是以下 xml 配置:

<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="interceptors">
    <list><ref bean="flashScopeInterceptor"/></list>
  </property>
</bean>

I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.

the main idea for the flash scope is to store data from one controller till next redirect in second controller

Please refer to my answer on the custom scope question:

Spring MVC custom scope bean

The only thing that is missing in this code is the following xml configuration:

<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
  <property name="interceptors">
    <list><ref bean="flashScopeInterceptor"/></list>
  </property>
</bean>
瑾兮 2024-12-12 06:13:28

您可以使用 org.springframework.web.servlet.mvc.support.RedirectAttributes 来解决它。

这是我的控制器示例。

@RequestMapping(method = RequestMethod.POST)
    public String eligibilityPost(
            @ModelAttribute("form") @Valid EligibiltyForm form,
            Model model,
            RedirectAttributes redirectAttributes) {
        if(eligibilityService.validateEligibility(form)){
            redirectAttributes.addFlashAttribute("form", form);
            return "redirect:<redirect to your page>";
        }
       return "eligibility";
    }

在我的博客上阅读更多内容
http://mayurshah.in/596/如何重定向到页面保持模型值

You can resolve it by using org.springframework.web.servlet.mvc.support.RedirectAttributes.

Here is my controller sample.

@RequestMapping(method = RequestMethod.POST)
    public String eligibilityPost(
            @ModelAttribute("form") @Valid EligibiltyForm form,
            Model model,
            RedirectAttributes redirectAttributes) {
        if(eligibilityService.validateEligibility(form)){
            redirectAttributes.addFlashAttribute("form", form);
            return "redirect:<redirect to your page>";
        }
       return "eligibility";
    }

read more on my blog at
http://mayurshah.in/596/how-do-i-redirect-to-page-keeping-model-value

杀手六號 2024-12-12 06:13:28

我有同样的问题。

刷新页面后使用 RedirectAttributes,我的第一个控制器的模型属性已丢失。我以为这是一个错误,但后来我找到了解决方案。
在第一个控制器中,我在 ModelMap 中添加属性并执行此操作而不是“重定向”:

return "forward:/nameOfView";

这将重定向到另一个控制器,并保留第一个控制器的模型属性。

我希望这就是您正在寻找的。对不起我的英语

I had same problem.

With RedirectAttributes after refreshing page, my model attributes from first controller have been lost. I was thinking that is a bug, but then i found solution.
In first controller I add attributes in ModelMap and do this instead of "redirect":

return "forward:/nameOfView";

This will redirect to your another controller and also keep model attributes from first one.

I hope this is what are you looking for. Sorry for my English

二智少女 2024-12-12 06:13:28

如果您只想传递所有属性来重定向......

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}

If you want just pass all attributes to redirect...

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}
安稳善良 2024-12-12 06:13:28

也许你可以这样做:

不要在第一个控制器中使用模型。将数据存储在其他共享对象中,然后第二个控制器可以检索该数据。

看看这个这篇文章。这是关于类似的问题。

PS

您可能可以使用 session该共享数据的作用域 bean...

Maybe you could do it like this:

Don't use the model in first controller. Store data in some other shared object which could be then retrieved by second controller.

Look at this and this post. It's about the similar issue.

P.S.

You could probabbly use session scoped bean for that shared data...

メ斷腸人バ 2024-12-12 06:13:28

我使用了 @ControllerAdvice ,请检查是否在 Spring 3.X 中可用;我在 Spring 4.0 中使用它。

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}
放低过去 2024-12-12 06:13:28

通过使用@ModelAttribute,我们可以将模型从一个控制器传递到另一个控制器

[输入到第一个控制器][1]

[]: https://i.sstatic.net/rZQe5.jpg
从jsp页面第一个控制器将表单数据与@ModelAttribute绑定到User Bean

@Controller
public class FirstController {
    @RequestMapping("/fowardModel")
    public ModelAndView forwardModel(@ModelAttribute("user") User u) {
        ModelAndView m = new ModelAndView("forward:/catchUser");
        m.addObject("usr", u);
        return m;
    }
}

@Controller
public class SecondController {
    @RequestMapping("/catchUser")
    public ModelAndView catchModel(@ModelAttribute("user")  User u) {
        System.out.println(u); //retrive the data passed by the first contoller
        ModelAndView mv = new ModelAndView("userDetails");
        return mv;
    }
}

By using @ModelAttribute we can pass the model from one controller to another controller

[ Input to the first Controller][1]

[]: https://i.sstatic.net/rZQe5.jpg
from jsp page first controller binds the form data with the @ModelAttribute to the User Bean

@Controller
public class FirstController {
    @RequestMapping("/fowardModel")
    public ModelAndView forwardModel(@ModelAttribute("user") User u) {
        ModelAndView m = new ModelAndView("forward:/catchUser");
        m.addObject("usr", u);
        return m;
    }
}

@Controller
public class SecondController {
    @RequestMapping("/catchUser")
    public ModelAndView catchModel(@ModelAttribute("user")  User u) {
        System.out.println(u); //retrive the data passed by the first contoller
        ModelAndView mv = new ModelAndView("userDetails");
        return mv;
    }
}
肥爪爪 2024-12-12 06:13:28

将所有模型属性作为查询字符串添加到重定向 URL。

Add all model attributes to the redirecting URL as query string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文