java - 添加之前检查 Controller 方法中是否存在模态属性

标签 java spring spring-mvc modelattribute

我有一个 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/

相关文章:

java - Spring无法加载xml配置文件

java - 在 Weblogic Server 中使用 JAXB 解码

java - IntelliJ IDEA 远程 JSP 调试?

java - 如何在 javafx 中打开组合框弹出窗口

database - OneToMany(fetch=FetchType.EAGER) 是否执行 N+1 个查询

java - 不访问日期选择器会出现转换错误

java - 以 Spring MVC 形式绑定(bind)的对象

java - Hibernate 5 和类型化条件查询 (JPA2)

使用 Kerberos 和 LDAP 的 Java Spring SSO 授权

java - Spring 属性(property)整合