大数跨境
0
0

SpringBoot中Controller接口参数还可以这样玩?

SpringBoot中Controller接口参数还可以这样玩? Spring全家桶实战案例
2024-06-13
0
导读:SpringBoot关于Controller接口的这些知识点你知道吗?

环境:SpringBoot3.2.5



1. Optional包装参数

请求参数通过java.util.Optional包装

@GetMapping("/optional")public Object optional(Optional<String> name) {  return String.format("请求参数: %s", name.orElse("")) ;}

通过Optional接受参数,效果等同于

public Object optional(@RequestParam(required=false) String name){}

与将required设置为false效果一样(@RequestHeader同样

2. 便捷获取Servlet API

在请求参数中你可以使用WebRequestNativeWebRequest两个任意对象来获取Request,Response,Session等对象。

@GetMapping("/servlet/api")public Object servletApi(WebRequest request, NativeWebRequest webRequest) {  String name = request.getParameter("name") ;  // 获取Servlet API  HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class) ;  HttpServletResponse resp = webRequest.getNativeResponse(HttpServletResponse.class) ;  HttpSession session = webRequest.getNativeRequest(HttpSession.class) ;  return "servlet api" ;}

当然你可以直接写你需要的具体对象

public Object servletApi(HttpServletRequest req,   HttpServletResponse resp) {  // ...}

NativeWebRequest本身提供了很多通用的方法,并且还可以获取其它对象,使用起来更加方便。

3. 获取当前认证用户

你的请求参数还可以使用java.security.Principal该对象用来获取当前请求中已经认证过的用户信息。这尤其在使用Spring Security时非常有用,在Security中的Authentication接口实现了Principal。

@GetMapping("/principal")public Object principal(Principal principal) {  return principal ;}

输出如下

4. 获取请求其它信息

你还可以非常方便的获取当前请求Method及Locale等信息。

@GetMapping("/other")public Object other(HttpMethod method, Locale locale) {  return method.name() + ", " + locale.toString() ;}// 输出GET, zh_CN

除此之外,你还可以获取时区信息java.util.TimeZonejava.time.ZoneId。

5. 读取输入流

将请求body中的内容以流InputStream形式获取。

@PostMapping("/inputStream")public Object inputStream(InputStream is) throws Exception {  return String.format("读取到内容: %s",     StreamUtils.copyToString(is, StandardCharsets.UTF_8)) ;}

输出结果

6. 获取Header&Body

通过HttpEntity获取请求header及body内容信息

@PostMapping("/httpentity")public Object httpentity(HttpEntity<String> entity) {  return Map.of(    "headers", entity.getHeaders(),     "body", entity.getBody()  ) ;}

输出结果

7. 获取当前请求URI

如果你想获取当前请求的Schema,Host,Port,上下文,那么你可以通过如下参数获取

@GetMapping("/uri")public Object uri(UriComponentsBuilder builder) {  return builder.toUriString() ;}

输出结果

http://localhost:9001/api

只包含了schema://host:port/context

8. 获取请求的部分

如果你的请求是multipart/form-data,那么你可以通过如下方式获取部分请求信息

@PostMapping("/requestpart")public Object requestpart(@RequestPart("user"String user) {  return user ;}

请求结果

你还可以以JSON对象读取,如下:

public Object requestpart(@RequestPart("user") User user)

注意,对象接受时,你需要设置每part的Content-Type

Content-Type: multipart/mixed
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7VpContent-Disposition: form-data; name="user"Content-Type: application/json; charset=UTF-8Content-Transfer-Encoding: 8bit
{  "age": 20,  "name""张三"}

没有设置Content-Type将会抛出415错误。

9.重定向保存属性

指定在发生重定向时使用的属性(即要附加到查询字符串中的属性)以及要在重定向请求期间临时存储的属性。

@PostMapping("/")public String handleFileUpload(RedirectAttributes redirectAttributes) {  // 重定向后能够获取到这里指定的属性信息  redirectAttributes.addFlashAttribute("message""You successfully uploaded file!");  // 重定向  return "redirect:/";}

通过该种方式,重定向后页面中也能获取设置的属性信息。

以上是本篇文章的全部内容,如对你有帮助帮忙点赞+转发+收藏

推荐文章

警惕!SpringBoot错误发布事件,造成死锁Deadlock

SpringBoot3第三方接口调用10种方式,最后一种你肯定没用过

严重!Spring AOP Bug导致切面重复执行

这才是Spring为什么不支持static字段注入的原因【源码分析】

Spring Boot 3太强:全新Controller接口定义方式

基于SpringBoot通过3种方式轻松搞定敏感字段加密处理

从SpringBoot2.7开始自动配置发生哪些变化?你都知道吗?

必须掌握SpringBoot强大的日志功能

SpringBoot3使用虚拟线程一定要小心了

不知道这些不要说玩转了Controller接口

OpenFeign高级用法:这些强大的功能你用过吗?

SpringBoot整合RSocket实时数据通信

【声明】内容源于网络
0
0
Spring全家桶实战案例
Java全栈开发,前端Vue2/3全家桶;Spring, SpringBoot 2/3, Spring Cloud各种实战案例及源码解读
内容 832
粉丝 0
Spring全家桶实战案例 Java全栈开发,前端Vue2/3全家桶;Spring, SpringBoot 2/3, Spring Cloud各种实战案例及源码解读
总阅读195
粉丝0
内容832