Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass model data from one controller to another controller spring

I have my controller-A class like this:

@PostMapping("/otp")
public String otpSubmit(@RequestParam("token") String token, HttpSession session, Model model) throws IOException {

Long enrollment = (Long) session.getAttribute("enrollment");
BaseResponse otpResponse = otpRestClient.validateOTP(enrollment, token);
if(otpResponse.getCode().equals("1020")) {
    model.addAttribute("object", otpResponse.getPayload());
    return "redirect:/password";
}

model.addAttribute("errorCode", otpResponse.getCode());
model.addAttribute("errorMessage", otpResponse.getMessage());

return "/otp";
}

What I want is simple (I think) pass the model.addAttribute("object", otpResponse.getPayload()); to controller-B class so I can access that data in the other view.

How can I inject this into controller-B class?.

like image 677
Alex Avatar asked May 11 '26 02:05

Alex


1 Answers

By adding redirectAttributes we can pass model data

Here is the Controller one.

  public String controlMapping1(
    @ModelAttribute("mapping1Form") final Model model, 
    final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("mapping1Form", model);
return "redirect:mapping2";

}

Here is Controller2

public String controlMapping2(
    @ModelAttribute("mapping1Form") final Model model) {
model.addAttribute("transformationForm", model);
return "view_name";  

}

like image 66
balu Avatar answered May 13 '26 15:05

balu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!