SpringBoot - @ControllerAdvice的使用详解2(添加全局数据 @ModelAttribute)
二、添加全局数据(搭配 @ModelAttribute)
1,设置全局数据
(1)@ControllerAdvice 是一个全局数据处理组件,因此也可以在 @ControllerAdvice 中配置全局数据,使用 @ModelAttribute 注释进行配置。
(1)这里我们在全局配置中添加了两个方法:
- message 方法:返回一个 String。
- userInfo 方法:返回一个 map。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.example.demo; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import java.util.HashMap; import java.util.Map; @ControllerAdvice public class GlobalConfig { @ModelAttribute (value = "msg" ) public String message() { return "欢迎访问 hangge.com" ; } @ModelAttribute (value = "info" ) public Map<String, String> userinfo() { HashMap<String, String> map = new HashMap<>(); map.put( "name" , "hangge" ); map.put( "age" , "100" ); return map; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package com.example.demo; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import java.util.HashMap; @ControllerAdvice public class GlobalConfig { @ModelAttribute public void addAttributes(Model model) { model.addAttribute( "msg" , "欢迎访问 hangge.com" ); HashMap<String, String> map = new HashMap<>(); map.put( "name" , "hangge" ); map.put( "age" , "100" ); model.addAttribute( "info" , map); } } |
2,获取全局数据
(1)在任意请求的 Controller 中,方法参数中通过 @ModelAttribute 可以获取指定的全局数据,样例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package com.example.demo; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping; import java.util.Map; @RestController public class HelloController { @GetMapping ( "/hello" ) public String hello( @ModelAttribute ( "msg" ) String msg, @ModelAttribute ( "info" ) Map<String, String> info) { String result = "msg:" + msg + "<br>" + "info:" + info; return result; } } |

(2)我们也可以在请求的 Controller 方法参数中的 Model 获取所有的全局数据,下面代码的结果同上面的一样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.example.demo; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping; import java.util.Map; @RestController public class HelloController { @GetMapping ( "/hello" ) public String hello(Model model) { Map<String, Object> map = model.asMap(); String msg = map.get( "msg" ).toString(); Map<String, String> info = (Map<String, String>)map.get( "info" ); String result = "msg:" + msg + "<br>" + "info:" + info; return result; } } |