springboot 配置全局响应数据_SpringBoot - @ControllerAdvice的使用详解2(添加全局数据 @ModelAttribute)...

本文介绍了如何在SpringBoot中使用@ControllerAdvice和@ModelAttribute实现全局响应数据配置。通过在GlobalConfig类中定义@ModelAttribute注解的方法,设置全局的message和userinfo数据。在Controller中,可以通过@ModelAttribute注解获取这些全局数据,或者从Model中获取所有全局数据。
摘要由CSDN通过智能技术生成

二、添加全局数据(搭配 @ModelAttribute)

1,设置全局数据

(1)@ControllerAdvice 是一个全局数据处理组件,因此也可以在@ControllerAdvice 中配置全局数据,使用 @ModelAttribute注释进行配置。

(1)这里我们在全局配置中添加了两个方法:

message方法:返回一个 String。

userInfo方法:返回一个 map。

(2)这两个方法有一个注解@ModelAttribute,其中 value属性表示这条返回数据的 key,而方法的返回值是返回数据的 value。

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 userinfo() {

HashMap map = new HashMap<>();

map.put("name", "hangge");

map.put("age", "100");

return map;

}

}

(2)当然 @ModelAttribute也可以不写 value参数,直接在方法中对全局 Model设置 key和 value。下面代码的效果同上面是一样的:

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 map = new HashMap<>();

map.put("name", "hangge");

map.put("age", "100");

model.addAttribute("info", map);

}

}

2,获取全局数据

(1)在任意请求的 Controller中,方法参数中通过 @ModelAttribute可以获取指定的全局数据,样例代码如下:

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 info) {

String result = "msg:" + msg + "
" + "info:" + info;

return result;

}

}

(2)我们也可以在请求的 Controller方法参数中的 Model获取所有的全局数据,下面代码的结果同上面的一样:

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 map = model.asMap();

String msg = map.get("msg").toString();

Map info = (Map)map.get("info");

String result = "msg:" + msg + "
" + "info:" + info;

return result;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值