Question

I have a spring controller that I want a method to handle a certain request and then redirect to another one with keeping some value attached, so I will use RedirectAttributes on the first one and @ModalAttribute on the second, but the thing is I will not always have this modal attribute existing so I want to add it only if it exists.

@RequestMapping("/main")
public String getMain(Model model,HttpSession session,@ModalAttribute List<Loans> loansList){
    if(session.getAttribute("user") != null){
        if(session.getAttribute("current_start")!=null){
            model.addAttribute("loans",loanDao.findAll((Integer) session.getAttribute("current_start")));
        } else {
            model.addAttribute("loans",loanDao.findAll(0));
            session.setAttribute("current_start",0);
        }
        model.addAttribute("loan",new Loan());
        model.addAttribute("countries",countryDao.findAll());
        model.addAttribute("types",typeDao.findAll());
        session.setAttribute("total_loans_number", loanDao.findCount());
        return "main";
    } else {
        return "redirect:index";
    }
}

and the redirecting one one is

@RequestMapping(value = "/search")
public String searchLoans(Model model,RedirectAttributes redirectAttributes,
                          @RequestParam String keyword){
    redirectAttributes.addAttribute("loansList",loanDao.findAll(keyword));
    return "redirect:/main";
}

but here the @ModalAttribute fails because it sometimes does not exist,sometimes I request main with out the loansList, how to make a condition to add it only if it exists ? or how to do this correctly ?

Était-ce utile?

La solution

you can let spring populate your model attributes using @ModalAttribute annotation on methods:

@ModalAttribute("results")
public List<Loans> populateLoans() {
    return new ArrayList<Loans>();
}

@RequestMapping("/main")
public String getMain(Model model,HttpSession session,@ModalAttribute("results") List<Loans> loansList){
    if (CollectionUtils.isNotEmpty(loanList)) {
        // do something if the loan list is not empty. 
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top