Passing a variable from @Controller to @ControllerAdvice to SpringMVC

I created @ControllerAdviceone that should set me some attribute of the model.

@ModelAttribute
public void globalAttributes(Model model) {
       model.addAttribute("pageId", PAGE_ID);
}

This is a general example of what I need, and PAGE_ID represents some variable that the actual controller should set. Since it @ControllerAdviceis executed in front of the controller, how can I declare this variable and use it in the Recommendations section? If it’s even possible.

+4
source share
1 answer

I think the best solution would be to use some kind of abstract template for your controller.

public abstract class AbstractController {

    @ModelAttribute
    public void globalAttributes(Model model) {
       model.addAttribute("pageId", getPageId());
    }

    abstract String getPageId();
}

public class MyController extends AbstractController {

    @Override
    public String getPageId() {
       return "MyPageID"
    }

    //..your controller methods
}
0
source

Source: https://habr.com/ru/post/1619195/


All Articles