Springboot 之 HandlerMethodReturnValueHandler 运用

简介: Springboot 之 HandlerMethodReturnValueHandler 运用

简介

现在项目中大部分采用前后端分离的架构,采用这种架构的项目,在返回数据时,几乎都是采用返回 json 格式的数据。而 spring 中返回 json 格式的数据一般采用 @RestController 或者 @ResponseBody 注解。代码样例

@ResponseBody
@RequestMapping("/reqBody")
public ResultInfo<Map<String, Object>> reqBody(){
    ResultInfo<Map<String, Object>> resultInfo = new ResultInfo<>();
    resultInfo.setCode(200);
    resultInfo.setMessage("success");
    Map<String, Object> map = new HashMap<>();
    map.put("userId", 100);
    map.put("tenantId", 1001);
    map.put("userName", "bug弄潮儿");
    resultInfo.setBody(map);
    return resultInfo;
  }

今天定义一个注解读返回的 json 进行加密,来运用 HandlerMethodReturnValueHandler

pom.xml 文件引入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.olive</groupId>
  <artifactId>springmvc-response-body</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>springmvc-response-body</name>
  <url>http://maven.apache.org</url>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.14</version>
    <relativePath /> <!-- lookup parent from repository -->
  </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba.fastjson2</groupId>
      <artifactId>fastjson2</artifactId>
      <version>2.0.14</version>
    </dependency>
  </dependencies>
</project>

定义加密注解

package com.olive.annotation;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Encrypted {
boolean value() default true;
}

Encrypted 注解,该注解是一个标识注解;如果打上该注解标识加密

统一返回定义

主要包含 code、message 和 body 属性定义

package com.olive.dto;
import lombok.Data;
import java.io.Serializable;
@Data
public class ResultInfo<T> implements Serializable {
public  int code;
public String message;
private T body;
private boolean encrypt;
}

自定义 ResponseBodyHandler

该类实现 HandlerMethodReturnValueHandler 类,主要对 @RestController 或者 @ResponseBody 注解进行解析

package com.olive.config;
import com.alibaba.fastjson2.JSON;
import com.olive.annotation.Encrypted;
import com.olive.dto.ResultInfo;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.nio.charset.StandardCharsets;
public class ResponseBodyHandler implements HandlerMethodReturnValueHandler {
protected final HandlerMethodReturnValueHandler handlerMethodReturnValueHandler;
public ResponseBodyHandler(HandlerMethodReturnValueHandler handlerMethodReturnValueHandler){
this.handlerMethodReturnValueHandler = handlerMethodReturnValueHandler;
    }
@Override
public boolean supportsReturnType(MethodParameter returnType) {
//如果被@ResponseBody注解修饰的 返回true
return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) || returnType.hasMethodAnnotation(ResponseBody.class))
                && returnType.hasMethodAnnotation(Encrypted.class);
    }
@Override
public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
if(returnValue instanceof ResultInfo){
            ResultInfo<?> resultInfo = (ResultInfo<?>)returnValue;
            ResultInfo<String> newResultInfo = new ResultInfo<>();
            newResultInfo.setCode(resultInfo.getCode());
            newResultInfo.setMessage(resultInfo.getMessage());
            newResultInfo.setEncrypt(true);
            newResultInfo.setBody(Base64Utils.encodeToString(JSON.toJSONString(resultInfo.getBody()).getBytes(StandardCharsets.UTF_8)));
//ResponseBody注解执行器
            handlerMethodReturnValueHandler.handleReturnValue(newResultInfo,
                    returnType, mavContainer, webRequest);
        }else{
            handlerMethodReturnValueHandler.handleReturnValue(returnValue,
                    returnType, mavContainer,  webRequest);
        }
    }
}

注册 ResponseBodyHandler 到 controller 返回值处理器里,即添加自己的返回值处理器

package com.olive.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebConfig implements InitializingBean {
@Autowired
private RequestMappingHandlerAdapter adapter;
@Override
public void afterPropertiesSet() throws Exception {
        List<HandlerMethodReturnValueHandler> unmodifiableList = adapter.getReturnValueHandlers();
        List<HandlerMethodReturnValueHandler> list = new ArrayList<>(unmodifiableList.size());
for (HandlerMethodReturnValueHandler returnValueHandler : unmodifiableList) {
if (returnValueHandler instanceof RequestResponseBodyMethodProcessor) {
//将RequestResponseBodyMethodProcessor 实际返回值替换为自定义的,实际执行为RequestResponseBodyMethodProcessor
//重要
HandlerMethodReturnValueHandler handler = new ResponseBodyHandler(returnValueHandler);
                list.add(handler);
            } else {
                list.add(returnValueHandler);
            }
        }
        adapter.setReturnValueHandlers(list);
    }
}

测试

编写 Springboot 启动引导类

package com.olive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * https://cloud.tencent.com/developer/article/1616704
 *
 * @author 2230
 *
 */
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
    }
}

编写测试 Controller

package com.olive.controller;
import java.util.HashMap;
import java.util.Map;
import com.olive.annotation.Encrypted;
import com.olive.dto.ResultInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
  @Encrypted
  @RequestMapping("/reqBody")
  public ResultInfo<Map<String, Object>> reqBody(){
    ResultInfo<Map<String, Object>> resultInfo = new ResultInfo<>();
    resultInfo.setCode(200);
    resultInfo.setMessage("success");
    Map<String, Object> map = new HashMap<>();
    map.put("userId", 100);
    map.put("tenantId", 1001);
    map.put("userName", "bug弄潮儿");
    resultInfo.setBody(map);
    return resultInfo;
  }
}

通过 HandlerMethodReturnValueHandler 可以对返回的数据进行进一步的封装,减少在业务代码中进行重复的返回值处理。例如,文章中的对返回数据进行统一加密。

相关文章
|
JSON NoSQL Java
springboot整合redis超级详解
springboot整合redis超级详解
503 0
|
Java API Maven
IDEA+Maven+多个Module模块(创建多模块SpringBoot整合项目)
IDEA+Maven+多个Module模块(创建多模块SpringBoot整合项目)
1925 1
|
10月前
|
人工智能 监控 安全
OpenClaw/ClawdBot傻瓜式部署终极指南:全平台接入(QQ/飞书/钉钉/企业微信)GET 24小时无休 AI 数字员工
2026年,OpenClaw(原ClawdBot)的爆火彻底重构了人们对AI工具的认知——这个能自主操作电脑、7×24小时无休的AI数字员工,不仅能帮你清理邮件、抢票、写代码,还能通过手机随时随地遥控,让“躺着干活”成为现实。网友们的花式玩法更是刷新想象:有人用它清理上万封邮件,压缩45%收件箱容量;有人让它每隔几秒刷新抢演唱会门票,刷到自动下单;还有程序员在地铁上发一条消息,就让它写完并部署好一个完整的网页工具。甚至连苹果Mac Mini都因它卖断货,只因大家需要一台24小时不关机的小主机跑起专属AI助理。
1623 5
|
12月前
|
JSON 前端开发 Java
Spring Boot 封装统一返回的数据结构
本课讲解如何设计统一的JSON响应结构,通过泛型类`JsonResult&lt;T&gt;`封装返回数据,规范包含code、msg、data的标准格式,提升前后端协作效率与API可维护性。
|
缓存 NoSQL Linux
在CentOS 7系统中彻底移除MongoDB数据库的步骤
以上步骤完成后,MongoDB应该会从您的CentOS 7系统中被彻底移除。在执行上述操作前,请确保已经备份好所有重要数据以防丢失。这些步骤操作需要一些基本的Linux系统管理知识,若您对某一步骤不是非常清楚,请先进行必要的学习或咨询专业人士。在执行系统级操作时,推荐在实施前创建系统快照或备份,以便在出现问题时能够恢复到原先的状态。
1552 79
|
SQL 关系型数据库 API
MCP Server 的开发实践- Alibaba Cloud RDS OpenAPI MCP Server
本文介绍了基于阿里云 RDS OpenAPI 实现的 MCP Server(Model Context Protocol Server)架构与开发实践。该中间件使大语言模型(LLM)可通过自然语言调用 RDS 服务,实现数据库实例的创建、查询、配置等操作。通过 OpenAPI 接入、SQL 执行与大模型交互三大模块的协同工作,MCP Server 实现了 AI 助手对云数据库的自动化管理,提升易用性与安全性。
1023 0
|
SQL Java 数据库连接
成功解决:was not registered for synchronization because synchronization is not active
这篇文章是关于解决Mybatis在同步过程中出现"was not registered for synchronization because synchronization is not active"错误的技术博客。
成功解决:was not registered for synchronization because synchronization is not active
mybatis复习01,简单配置让mybatis跑起来
文章介绍了MyBatis的基本概念、历史和特点,并详细指导了如何配置MyBatis环境,包括创建Maven项目、添加依赖、编写核心配置文件、创建数据表和实体类、编写Mapper接口和XML配置文件,以及如何编写工具类和测试用例。
mybatis复习01,简单配置让mybatis跑起来
|
Docker 容器
docker的导入本地镜像和导出本地镜像
本文介绍了如何使用Docker对本地镜像进行导入和导出操作,包括从本地导入`nginx.tar`镜像以及将`open-webui`镜像导出并压缩为`open-webui.tar.gz`。
2148 1
|
安全 IDE Java
MapStruct-JavaBean映射工具使用指南
MapStruct-JavaBean映射工具使用指南
550 9