Search code examples
javaspring-bootspring-mvcthymeleaf

Dropdown used on multiple pages, should I componentize it?


I got this dropdown that will be utilized on some pages and I am concerning if I should componentize it and include it on each page or if I call the dropdown service on each service that is needed. I building a spring mvc with thymeleaf


Solution

  • In case when you have a dropdown, or any other html element for that matter, that needs to appear on several pages, it makes sense to place that element(s) inside a thymeleaf fragment so as to avoid code duplication. Not only do you avoid code duplication, but your code will become easier to maintain as well (because there's less code to maintain).

    <div  th:fragment="dropdownFragment">
    ....
    <select> 
    <th:block th:each="item : ${dropdownItems}">
      <option th:value="${item}" th:text="${item}"></option>
    </th:block>
    </select>
    </div>
    

    In order to reduce the number of trips to the database, we should cache our data. Possibly the easiest way to do this is to make use of the built in HttpSession object (especially when our data is relatively small).The code might look something like

       HttpSession session = request.getSession();
      //code to retrive data from the db
      session.setAttribute("dropdownItems", dropdownItems);
    

    The session object can be referenced in thymeleaf as #{session.some_object} but this has been deprecated since Thymeleaf 3.1. For this reason, it's best to copy the session attribute into a Model (or ModelAndView) object, which can then be referenced as ${modelObject}.

    @GetMapping("/getItems")
    public ModelAndView getDropdownItems(HttpSession session )
      ModelAndView mv = new ModelAndView();
      mv.setViewName("someView");
     //this assumes that you already have a session with dropdownItemsattribute
      mv.addObject("dropdownItems", session.getAttribute("dropddownItems"));
      return mv;
     }
     
    

    Hope this helps.