我有一个 spring Controller ,我想要一个方法来处理某个请求,然后重定向到另一个请求并保留一些附加值,所以我将在第一个请求上使用 RedirectAttributes,在第二个请求上使用 @ModalAttribute,但问题是我不会总是让这个模态属性存在,所以我只想在它存在时添加它。
@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";
}
}
一一重定向是
@RequestMapping(value = "/search")
public String searchLoans(Model model,RedirectAttributes redirectAttributes,
@RequestParam String keyword){
redirectAttributes.addAttribute("loansList",loanDao.findAll(keyword));
return "redirect:/main";
}
但是这里 @ModalAttribute 失败,因为它有时不存在,有时我请求 main 而不包含贷款列表,如何设置一个条件仅在存在时添加它?或者如何正确执行此操作?
最佳答案
你可以让 spring 使用方法上的 @ModalAttribute 注释来填充你的模型属性:
@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.
}
}
关于java - 添加之前检查 Controller 方法中是否存在模态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18208106/