Issue
For note, I'm using Thymeleaf & Spring 2.5.4. For example, I've three different "banner" entities that I need to show on one page. There are "mainBanner"
, "backgroundBanner"
and "newsBanner"
. First of all, is it the right way to combine controllers in one (in the frame of banner entities)? Or is there exist any standard that says we must write controllers separately for each entity? But the main question is how to write @RequestingMapping
correctly for the banner page? I have the banner page ("/admin/banners/"
) where should be three tables of those entities. As I understand I need to create BannerPageController with @RequestingMapping("/admin/banners/")
, isn't it? Hoping for any help in solving
I've written controllers this way:
#MainBannerController.class
@Controller
@RequestMapping("admin/banners/main/")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MainBannerController {
...
#BackgroundBannerController.class
@Controller
@RequestMapping("admin/banners/background/")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MainBannerController {
...
#NewsBannerController.class
@Controller
@RequestMapping("admin/banners/news/")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MainBannerController {
...
Moreover, how to get 3 different models for one view? #BannerController.class ???
@Controller
@RequestMapping("admin/banners/main/")
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class MainBannerController {
private final MainBannerService mainBannerService;
private final MainBannerService mainBannerService;
private final MainBannerService mainBannerService;
// How to get 3 different models for one view?
@GetMapping({"/", ""})
public ModelAndView allBanners() {
// new ModelAndView("/admin/banners/index", "mainBanners", mainBannerService.getAllMainBanners());
// new ModelAndView("/admin/banners/index", "backgroundBanners", backgroundBannerService.getAllBackgroundBanners());
// new ModelAndView("/admin/banners/index", "newsBanners", newsBannerService.getAllNewsBanners());
return null;
}
Solution
create your modelAndView
ModelAndView modelAndView = new ModelAndView("/admin/banners/index");
then add as many object as you want, under a different name each
modelAndView.addObject("mainBanners", mainBannerService.getAllMainBanners());
modelAndView.addObject("backgroundBanners",mainBannerService.getAllBackgroundBanners());
return modelAndView;
Answered By - scav