Boolean condition with Thymeleaf and Spring

后端 未结 2 1785
暗喜
暗喜 2021-02-13 20:33

I\'d like to add an error flag in my web page. How can I to check if a Spring Model attribute is true or false with Thymeleaf?

2条回答
  •  再見小時候
    2021-02-13 21:14

    You can access model attributes by using variable expression (${modelattribute.property}).

    And, you can use th:if for conditional checking.

    It looks like this:

    Controller:

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class MyController {
    
      @RequestMapping("/foo")
      public String foo(Model model) {
        Foo foo = new Foo();
        foo.setBar(true);
        model.addAttribute("foo", foo);
        return "foo";
      }
    
    }
    

    HTML:

    
    
    
    
    
      

    bar is true.

    bar is false.

    Foo.java

    public class Foo {
      private boolean bar;
    
      public boolean isBar() {
        return bar;
      }
    
      public void setBar(boolean bar) {
        this.bar = bar;
      }
    
    }
    

    Hope this helps.

提交回复
热议问题