如何在spring中将requestparam传递给另一个方法

时间:2017-11-08 05:33:39

标签: java spring spring-mvc annotations

我正在尝试将我的参数传递给另一个方法并将其保存到我各自的存储库中。我想将checkoutView中的参数传递给doOrder。我该怎么做?

这是我的控制器代码:

@Controller
@RequestMapping(value = "/checkout")
public class CheckoutController {


@Autowired
ProductRepository pRepo;

@Autowired
CustomerRepository cRepo;

@Autowired
InventoryRepository iRepo;

@RequestMapping(value = "", method=RequestMethod.POST)
public ModelAndView checkoutView(@RequestParam(value="val-name") String prodname, @RequestParam(value="val-qty") int qty, @RequestParam(value="val-price") double price, @RequestParam(value="amount") String amount) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("customerEntity", new CustomerEntity());
    mav.setViewName("/checkout");
    return mav;
}

@RequestMapping(value="/new",method = RequestMethod.POST)
public String doOrder(@ModelAttribute CustomerEntity customerEntity, @ModelAttribute ProductEntity productEntity) {
//perform a save to their repositories
    return "redirect:/product-list";
  }

}

2 个答案:

答案 0 :(得分:0)

您可以尝试使用RedirectAttributes春天。它是Model的子接口。

这是将属性传递给重定向目标的首选方法。

答案 1 :(得分:0)

我太笨了。我只需要将它转移到方法中。

@RequestMapping(value = "", method=RequestMethod.POST)
public ModelAndView checkoutView() {
    ModelAndView mav = new ModelAndView();
    mav.addObject("customerEntity", new CustomerEntity());
    mav.setViewName("/checkout");
    return mav;
}

@RequestMapping(value="/new",method = RequestMethod.POST)
public String doOrder(@ModelAttribute CustomerEntity customerEntity, @ModelAttribute ProductEntity productEntity, @RequestParam(value="val-name") int prodname, @RequestParam(value="val-qty") int qty, @RequestParam(value="amount") double amount) {

    //perform a save to their repositories
    return "redirect:/product-list";
}