Controller接口還能這樣玩,你會玩了嗎?
環(huán)境:SpringBoot3.2.5
1. 自己控制輸出內(nèi)容
接口參數(shù)可以直接使用OutputStream或Writer類型的參數(shù),這樣你的接口可以不用有任何的返回值,直接通過這2個對象進行輸出內(nèi)容,如下示例:
@GetMapping("/index")
public void index(OutputStream os, HttpServletResponse response) throws Exception {
response.setContentType("text/plain;charset=utf-8") ;
os.write("中國????".getBytes()) ;
}
輸出結(jié)果
圖片
2. 自行讀取請求body
當你需要自己解析處理請求body內(nèi)容時,你可以將參數(shù)定義為InputStream或Reader類型,如下示例:
@PostMapping("/index")
public void index(InputStream is, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=utf-8") ;
StringBuilder sb = new StringBuilder() ;
String line = null ;
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8) ;
BufferedReader br = new BufferedReader(isr) ;
while ((line = br.readLine()) != null) {
sb.append(line) ;
}
response.getWriter().println(sb.toString()) ;
}
輸出結(jié)果:
圖片
3. 表達式參數(shù)
通常接口參數(shù)都是用來接收用戶輸入的數(shù)據(jù),不過你還可以將參數(shù)值"固定"了,通過@Value注解來獲取配置的數(shù)據(jù)信息,如下示例:
@GetMapping("/index")
public Object index(
@Value("${pack.controller.params.version:}") String version) {
return version ;
}
配置文件
pack:
controller:
params:
version: 1.0.1
輸出結(jié)果:
圖片
即便請求參數(shù)中有version參數(shù)值也不會影響接口。
你甚至還可以使用SpEL表達式
@GetMapping("/spel")
public Object spel(@Value("#{systemProperties['java.home']}") String javaHome) {
return javaHome ;
}
輸出結(jié)果:
圖片
4. body與header一起獲取
如果你不僅要獲取請求body還希望獲取所有逇請求header信息,那么你可以將參數(shù)類型定義為HttpEntity類型,如下示例:
@PostMapping("/index")
public Object index(HttpEntity<User> entity) {
System.out.printf("headers: %s%n", entity.getHeaders()) ;
return entity.getBody() ;
}
public static record User(Long id, String name) {
}
請求:
圖片
控制臺輸出:
圖片
5. 從當前安全上下文中獲取指定數(shù)據(jù)
這需要你當前環(huán)境使用了Spring Security。你可以直接在參數(shù)中獲取SecurityContext對象,也可以獲取當前安全上下文的任何關(guān)聯(lián)對象,比如獲取當前登錄人的name或者獲取角色信息等,如下示例:
@GetMapping("/name")
public Object name(
@CurrentSecurityContext(expression = "authentication.name") String name) {
return name ;
}
這里將獲取當前登錄用戶的name屬性值。
注:@CurrentSecurityContext注解從5.2版本才有的。
通過如下表達式還能獲取當前的角色信息
@CurrentSecurityContext(expression = "authentication.authorities")
當然你也可以直接獲取當前的上下文對象
@CurrentSecurityContext SecurityContext context
不添加表達式屬性即可獲取當前安全上下文對象。
圖片
獲取角色信息。
6. 特殊的Map參數(shù)
你可以在參數(shù)中直接定義Map集合對象;而它并非是從請求中獲取所有的參數(shù)添加到Map,而是從模型屬性中獲取,如下示例:
// 由該注解來接收用戶請求的參數(shù)
@ModelAttribute("user")
public User init(User user) {
return user ;
}
@GetMapping("/index")
public Object index(Map<String, Object> map) {
// 獲取用戶輸入的參數(shù)
return map.get("user") ;
}
輸出結(jié)果
圖片
這里Map填充的是由@ModelAttribute標注方法設(shè)置的值。