How to add breadcrumb to Spring MVC?

2019-08-17 06:39发布

How can I add breadcrumb to all pages of Spring MVC? I suppose it would be a good question to ask as breadcrumbs are quite popular now and it might be the question of many others.

I've found this solution that is using dummiesmind.breadcrumb.springmvc.annotations, there is also a question on stackoverflow but I could not learn much except finding similar solution to the one that Ive found. Another solution is this one that is using JavaScript.

Does anyone have a better option to the ones I mentioned?

@Link(label="Sample Link", family="controllerFamily", parent="");                                                                  
@RequestMapping(value = "sample.do", method=RequestMethod.GET);
public ModelAndView sampleMethod(HttpSession session){...}

1条回答
Lonely孤独者°
2楼-- · 2019-08-17 07:23

What are you using to display your pages ? JSP ? Thymeleaf ?

The link you point to seems a good option or at least you can build something custom that works for you based on that. Using annotations keeps your code clean but you need to make sure you add them everywhere.

You could use an abstract controller where you define a method to create a ModelAndView object for all pages. You could add breadcrumbs that way :

protected ModelAndView createModelAndView(String pageName, BreadCrumb breadCrumb) {
    ModelAndView modelAndView = new ModelAndView(pageName);
    modelAndView.addObject("breadCrumb", breadCrumb);
    return modelAndView;
}

Of course you would need to call that method everytime in your implementation.

One usage of this would be to pass your request url as parameter and parse it to build breadcrumbs by associating text to each part of the path (using the current local to tanslate it). So for example "/admin/user/list" would give you Home >> Administration >> User management >> List of users. That should be easy to build.

查看更多
登录 后发表回答