How pass POST parameters from controller to anothe

2019-07-27 22:48发布

问题:

I have startController and start view. In this view I input number and amount and validate it. If validation was successful, I want pass this parameters(number and amount) to another controller, and after that make some operations with it, in this controller. I see two way:

  1. make this operations in first controller, in another methods and use second view for it. But my controller will very big and all logic will be this.

  2. create second controller and second view and pass parameters to this controller.

I make this:

@Controller
@RequestMapping("/")
public class StartController {

    @Autowired
    private ValidateService validateService;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView printWelcome() {
        ModelAndView modelAndView = new ModelAndView("start");
        return modelAndView;
    }

    @RequestMapping(value = "process", method = RequestMethod.POST)
    public ModelAndView process(HttpServletRequest request) {
        ModelAndView modelAndView;
        String phoneNumber = request.getParameter("phone_number");
        int amount = Integer.parseInt(request.getParameter("amount"));

        String result = validateService.validate(phoneNumber, amount);

        if (!result.equals("OK")) {
            modelAndView = new ModelAndView("start");
            modelAndView.addObject("result",result);
        }else {
            modelAndView = new ModelAndView("redirect:/check/process");
            modelAndView.addObject("phone_number", phoneNumber);
            modelAndView.addObject("amount",amount);
        }
        return modelAndView;
    }

and if result != OK I redirect to new controller

@Controller
@RequestMapping("/check")
public class CheckController {

    @RequestMapping(value = "process", method = RequestMethod.GET)
    public ModelAndView process(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("check");
        String phoneNumber = request.getParameter("phone_number");
        int amount = Integer.parseInt(request.getParameter("amount"));
        return modelAndView;
    }
}

But I need pass parameters with RequestMethod.POST and it will not work. How do it?

回答1:

You can return a ModelAndView with parameters as follow:

return new ModelAndView("redirect:/check/process?phone_number="+yourPhoneNumber+"&amount="+amount)


回答2:

You can use forward to go to a new controller right? "forward:/test2?param1=foo&param2=bar"; Please see below link for more details. Spring forward with added parameters?



标签: spring-mvc