Springboot(4-11) @ControllerAdvice预设全局变量

第四章 @ControllerAdvice预设全局变量

任何一个controller里面都能获取到这个数据

1、首先创建 GlobalData

/**
 * @author ppf
 * @date 2020/7/7 10:59 下午
 */
@ControllerAdvice
public class GlobalData {
    @ModelAttribute(value = "info") //这样任何一个controller里面都能获取到这个数据 这样定义(这个value相当于是个key  返回值map  相当于value)
    public Map<String,Object> mydata(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","ppf");
        map.put("address","www.javaboy.org");
        return map;
    }
}

2、然后创建HelloController

/**
 * @author ppf
 * @date 2020/7/7 11:04 下午
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(Model model){
        Map<String, Object> map = model.asMap();
        Set<String> keySet = map.keySet();
        for (String key : keySet){
            System.out.println(key+":"+map.get(key));
        }

        return "hello";

    }
}

3、页面返回hello
着重看控制台显示。

2020-07-07 23:12:33.363  INFO 809 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 742 ms
2020-07-07 23:12:33.531  INFO 809 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-07-07 23:12:33.697  INFO 809 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-07-07 23:12:33.701  INFO 809 --- [           main] o.j.c.ControlleradviceApplication        : Started ControlleradviceApplication in 16.372 seconds (JVM running for 21.842)
2020-07-07 23:12:48.941  INFO 809 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-07-07 23:12:48.942  INFO 809 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-07 23:12:48.948  INFO 809 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 6 ms
info:{address=www.javaboy.org, name=ppf}

你可能感兴趣的:(java,Spring,boot)