gpt4 book ai didi

java - 所有方法的 Spring ModelMap 对象

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:31 25 4
gpt4 key购买 nike

为了更好地理解,这是一个示例 Spring Controller 代码:

@Controller  
public class SampleController {
protected String URL = "http://www.google.com/";


@RequestMapping(value = {listPath}, method = RequestMethod.GET)
public String list1( ModelMap modelMap) {
modelMap.addAttribute("url", URL);
return "list1View";
}

@RequestMapping(value = {listPath}, method = RequestMethod.GET)
public String list2( ModelMap modelMap) {
modelMap.addAttribute("url", URL);
return "list2View";
}

@RequestMapping(value = {listPath}, method = RequestMethod.GET)
public String list3( ModelMap modelMap) {
modelMap.addAttribute("url", URL);
return "list3View";
}

}

有更好的方法吗?将这个URL ModelMap对象传递给所有方法而不传入所有方法?

最佳答案

如果您想为所有 Controller 返回的模型传递通用值,请尝试将 @ControllerAdvice 与 @ModelAttribute 方法结合使用。

这里有一个快速解释。

Use @ModelAttribute at the method level to provide reference data for the model. @ModelAttribute annotated methods are executed before the chosen @RequestMapping annotated handler method. They effectively pre-populate the implicit model with specific attributes, often loaded from a database. Such an attribute can then already be accessed through @ModelAttribute annotated handler method parameters in the chosen handler method, potentially with binding and validation applied to it. In other words; a method annotated with @ModelAttribute will populate the specified “key” in the model. This happens BEFORE the @RequestMapping At Method Parameter level

关于java - 所有方法的 Spring ModelMap 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28525863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com