Search code examples
javaspringspring-bootspring-mvcthymeleaf

How to pass model attributes globally to avoid repeatable code in Spring controller?


I would like to ask you for some best practice to reduce the amount of repeatable code in my controller's methods - one of them is presented below.

I have quite a big and complex view with a lot of information and two forms. In every method of my controller (and there are quite a few) I have to pass the same attributes to my view (in post controllers even twice). I added a note SAME CODE in the code snippet below indicating identical pieces of code.

I wonder if there is any possibility to make a one global method in the controller gathering all attributes to be passed to the model and just reference it in any of particular methods?

I looked into ModelAndView or ModelMap, but cannot see those being suitable here.

Just want to avoid repeating this part:

Repeatable piece of code

model.addAttribute("hotels", hotelService.getAllHotels());
List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
model.addAttribute("rooms", roomsDto);
model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());

Full method with that piece of code appearing twice

@PostMapping("/hotels/{hotelId}/rooms")
    public String createRoomForHotelById(@ModelAttribute("room") @Valid NewRoomDto roomDto,
                                         BindingResult result,
                                         @PathVariable("hotelId") Long hotelId,
                                         Model model) {
        if(result.hasErrors()) {
            // SAME CODE
            model.addAttribute("hotels", hotelService.getAllHotels());
            List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
            model.addAttribute("rooms", roomsDto);
            model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
            //
            
            model.addAttribute("hotel", new NewHotelDto());
            LOG.info("Binding error: {}", result.toString());
            return "admin/dashboard";
        }
        
        // SAME CODE
        model.addAttribute("hotels", hotelService.getAllHotels());
        List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
        model.addAttribute("rooms", roomsDto);
        model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
        //
        
        LOG.info("AdminController: CreateRoomForHotelById: Created room: {}", roomDto.toString());
        
        roomDto.setHotelId(hotelId);
        roomService.createNewRoom(roomDto);
        
        return "redirect:/auth/admin/hotels/{hotelId}/rooms";
    }

Solution

  • You can also move the code from J Asgarov's answer into the same controller instead of another class annotated with @ControllerAdvice. That way that code will only be executed for @RequestMapping methods within that controller.

    For multiple values you could also do something like this:

    @ModelAttribute
    public void foo(Model model, @PathVariable(required = false) Long hotelId) {
            model.addAttribute("hotels", hotelService.getAllHotels());
            if (hotelId != null) {
                List<GetRoomDto> roomsDto = roomService.getAllRoomsByHotelId(hotelId);
                model.addAttribute("rooms", roomsDto);
            }
            model.addAttribute("roomTypes", roomTypeService.findAllRoomTypeNames());
    }
    

    But seeing your code I would rather suggest you move the repeated code into a private method and call it whenever you need those inside your model. Your method createRoomForHotelById for example causes a redirect, which basically discards everything you put in your model.