I am trying to get a object sent to a Spring-boot controller in one Class to be available in the model of another controller.
It seems like @SessionAttributes is for objects that are global (like the logged on user).
I have tried this on controller 1
@Component
@Controller
@SessionAttributes(value = { "user"})
public class FormController {
@GetMapping("/occurence/{occno}")
public String findOcc(@PathVariable String occno, OccViewModel occViewModel, Model model) {
Occ occ = occRepository.findByOccno(occno);
occViewModel.setOcc(occ);
occViewModel.setPersons(occPersonRepository.findOccPersonByOcc(occ.getId()));
List<OccPerson.OccRole> occRoles = Arrays.asList(OccPerson.OccRole.values());
model.addAttribute("occRoles", occRoles);
model.addAttribute("occViewModel", occViewModel);
model.addAttribute("countries", countries);
return "occ";
}
I have a button on this form which sends the user to this endpoint - I would like the same occViewModel to available to this endpoint on controller 2
@Component
@Controller
@SessionAttributes(value = { "user" })
public class PlanController {
@GetMapping("/newplan")
public String newPlan(Model model, OccViewModel occViewModel, HttpSession session) {
// create PlanViewModel DTO
Occ occ = new occVieModel.getOcc();
PlanViewModel planViewModel = new PlanViewModel;
planViewModel.setOcc(occ);
model.addAttribute(planViewModel);
//etc
}
I see there is @SessionAttributes but i do not understand in my first controller how I would even load it into the session if I dont know what Occ to get from the repo as it appears you need to @ModelAttribute prior to the handler - but the URI gives the occno?
I looked here also but it appeared do deal with the same class only and it wasn't clear how you would apply this to a id passed in on the URI.
@SessionAttributesis for temporary storing objects in between requests. It isn't meant to store objects for the lifetime of your application. If you really want it to have stored permanently just stick it in theHttpSessionelse just pass the id to the next controller (looks like you are only interested in theocc. You generally shouldn't be sharing models. Also do you really need 2 endpoints? I would expect something like this/occurence/{occno}/newplanand be in the same controller (judging from what you are trying to do in the other controller).