RequestBodyAdvice和注解方式进行统一参数处理demo
RequestBodyAdvice和注解方式进行统一参数处理demo
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HttpBodyDecrypt {
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mytester.entity.Student;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
@ControllerAdvice(basePackages = "com.example.mytester.controller")
public class GlobalRequestBodyAdvice implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println(">>>GlobalRequestBodyAdvice supports");
//只有打上注解标记的才执行 @HttpBodyDecrypt
boolean flag = methodParameter.hasMethodAnnotation(HttpBodyDecrypt.class);
if(flag) {
return true;
}
return false;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
System.out.println(">>>GlobalRequestBodyAdvice beforeBodyRead");
//方案2
return new XHttpInputMessage(inputMessage, "UTF-8");
//方案1
// StringBuilder sb = new StringBuilder();
// BufferedReader reader = null;
// try {
// reader = new BufferedReader(new InputStreamReader(inputMessage.getBody(), Charset.defaultCharset()));
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line);
// }
// } catch (IOException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// } finally {
// if (reader != null) {
// try {
// reader.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// JSONObject jsonObject = JSONObject.parseObject(sb.toString());
// System.out.println("覆盖之前的json串=" + jsonObject.toString());
//
// if (jsonObject != null){
// //改变
// if(jsonObject.get("name") != null) {
// jsonObject.put("name", "AMD");
// }
//
// //针对字段来处理
// String afterStr = jsonObject.toJSONString();
// System.out.println("覆盖之后的json串="+afterStr);
//
// //字符串转输入流
// InputStream rawInputStream = new ByteArrayInputStream(afterStr.getBytes());
// return new HttpInputMessage(){
//
// @Override
// public HttpHeaders getHeaders() {
// return inputMessage.getHeaders();
// }
//
// @Override
// public InputStream getBody() throws IOException {
// return rawInputStream;
// }
// };
// }
// return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println(">>>GlobalRequestBodyAdvice afterBodyRead");
return body;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
System.out.println(">>>GlobalRequestBodyAdvice handleEmptyBody");
return body;
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mytester.entity.Student;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import java.io.*;
import java.nio.charset.Charset;
public class XHttpInputMessage implements HttpInputMessage {
private HttpHeaders headers;
private InputStream body;
public XHttpInputMessage(HttpInputMessage httpInputMessage, String encode) throws IOException {
this.headers = httpInputMessage.getHeaders();
this.body = encode(httpInputMessage,httpInputMessage.getBody(), encode);
}
private InputStream encode(HttpInputMessage httpInputMessage, InputStream body, String encode) {
//省略对流进行编码的操作
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(body, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
if (jsonObject != null){
System.out.println("XHttpInputMessage获取json=" + jsonObject.toString());
Student student = JSONObject.parseObject(jsonObject.toString(), Student.class);
System.out.println("XHttpInputMessage修改之前的学生名称为:" + student.getName());
student.setName("AMD"); //改变值
String afterStr = JSON.toJSONString(student);
//字符串转输入流
InputStream rawInputStream = new ByteArrayInputStream(afterStr.getBytes());
return rawInputStream;
}
return body;
}
@Override
public InputStream getBody() throws IOException {
return body;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
}
public class ClassRoom {
private static final long serialVersionUID = -339516038496531943L;
private String sno;
private String name;
private String sex;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"sno='" + sno + '\'' +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
@RestController
public class TestController {
/**
* http://localhost:8080/addstudent4
* 参数:{"sno":"11124","name":"xiaoming","sex":"man"}
* 返回:
* Student{sno='11124', name='AMD', sex='man'}
*
* @param student
* @param request
* @return
*/
@HttpBodyDecrypt
@RequestMapping(value = "/addstudent4", method = RequestMethod.POST)
public String saveStudent4(@RequestBody ClassRoom student, HttpServletRequest request) {
return student.toString();
}
}
RequestBodyAdvice和注解方式进行统一参数处理demo的更多相关文章
- SpringMVC的controller方法中注解方式传List参数使用@RequestBody
在SpringMVC控制器方法中使用注解方式传List类型的参数时,要使用@RequestBody注解而不是@RequestParam注解: //创建文件夹 @RequestMapping(value ...
- Java 注解方式校验请求参数
1. 参数校验常用注解 注解 验证的数据类型 备注 Null 任意类型 参数值必须是 Null NotNull ...
- spirngboot 注解方式注入自定义参数
在代码中 @value("oracle.user") private String user; 在配置文件中 oracle.user=root
- 【SpringAop】【统一日志处理】注解方式理解以及使用
[注意:本次代码的demo会存在百度网盘,由于公司的保密,禁止上传,所以仅本人可见] 目前公司在做数据资产项目,数据质量部分使用到了springaop做统一日志处理,以前对这块有了解,有点模糊不清,今 ...
- 【spring mvc】spring mvc POST方式接收单个字符串参数,不加注解,接收到的值为null,加上@RequestBody,接收到{"uid":"品牌分类大”},加上@RequestParam报错 ---- GET方式接收单个参数的方法
spring mvc POST方式 接收单个参数,不加任何注解,参数名对应,接收到的值为null spring mvc POST方式 接收单个参数,加上@RequestBody,接收到参数格式:{&q ...
- spring 纯注解方式 与AOP
spring注解方式 以前我也使用过纯注解方式.现在在这里做个记录 我们先认识几个我们都耳熟能详的注解 @configuration :从spring3.0这个注解就可以用于定义配置类,可以替换xml ...
- 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法
spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...
- spring----IOC注解方式以及AOP
技术分析之Spring框架的IOC功能之注解的方式 Spring框架的IOC之注解方式的快速入门 1. 步骤一:导入注解开发所有需要的jar包 * 引入IOC容器必须的6个jar包 * 多引入一个:S ...
- Spring中的AOP注解方式和XML方式
应掌握内容:1. AOP的全名2. AOP的实现原理[静态代理和动态代理]3. 注解方式的配置4. 通知类型 A. 每种通知的特点和使用方式 B. 获取各种数据,方便日后操作5. 执行表 ...
- Spring系列之aAOP AOP是什么?+xml方式实现aop+注解方式实现aop
Spring系列之aop aop是什么?+xml方式实现aop+注解方式实现aop 什么是AOP? AOP为Aspect Oriented Programming 的缩写,意识为面向切面的编程,是通过 ...
随机推荐
- 链路分析 K.O “五大经典问题”
简介:链路分析是基于已存储的全量链路明细数据,自由组合筛选条件与聚合维度进行实时分析,可以满足不同场景的自定义诊断需求. 作者:涯海 链路追踪的 "第三种玩法" 提起链路追踪,大 ...
- 图像检索在高德地图POI数据生产中的应用
简介: 高德通过自有海量的图像源,来保证现实世界的每一个新增的POI及时制作成数据.在较短时间间隔内(小于月度),同一个地方的POI 的变化量是很低的. 作者 | 灵笼.怀迩 来源 | 阿里技术 ...
- [Go] VsCode 的 Golang 环境设置与代码跳转支持
终端执行: go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.io,direct WIndows下自定义指定 GOPATH 路径 ...
- css的animate做一个信号动画
html <div class="jump flex-fs fadeAndScaleIn"> <span></span> <span> ...
- win10的开机启动文件夹
1.在C:\Users(用户)\Administrator(当前用户名)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs(「开始」菜单)\P ...
- 谷歌 hackbar 不能使用的问题
谷歌 hackbar 不能使用的问题 下载 hackbar 插件:https://github.com/Mr-xn/hackbar2.1.3 解压文件,将其拖入 chrome 扩展程序中 点击详情,点 ...
- pdo类
testmysql.php <?php require_once "./mypdo.php"; //do something... //查一行 $id = 3; //$sql ...
- 记录——Qt Qcreator 顶部菜单栏的隐藏与恢复
问题 我有一个朋友(嗯~无中生友),手残点击了 QCreator 中视图下的这个玩意儿: 当人的眼神不好时,可能不会看到这些快捷键以及无视这些弹窗. 解决方案 快捷键 ctrl + alt + M 可 ...
- nim 9. 遍历文件夹
import std/[os, sugar] const fs = collect(for k in walkDir(r"d:\temp"): k.path) echo fs 文件 ...
- leaflet 用自定义pane实现图层顺序调整
在 Leaflet 中,map panes 隐式地将图层组合在一起,而开发者并不知道这一点.这种分组允许 Web 浏览器以比单独处理图层更有效的方式同时处理多个图层. Map panes 使用 z-i ...