设置全局变量:
使用方法:
1.在类上添加 @ControllerAdvice 注解
2.在方法上添加 @ModelAttribute(name = “变量名”) 注解
@Controller
@ControllerAdvice
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
/**
* 设置全局变量的值:将方法的返回值设为全局变量
*/
@ModelAttribute(name = "hello")
public String test1(){
String s = testService.getXxx();
return s;
}
获取变量:
/**
* 在任何一个Controller 的接口中,都可以获取到 "hello" 的数据
* 获取全局变量的值
*/
@RequestMapping(value = "/gethello", method = RequestMethod.GET)
@ResponseBody
public String test1(Model model){
Map<String, Object> stringObjectMap = model.asMap();
System.out.println(stringObjectMap);
System.out.println(stringObjectMap.get("hello").toString());
return stringObjectMap.get("hello").toString();
}