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 的缩写,意识为面向切面的编程,是通过 ...
随机推荐
- [FAQ] Mac Mini 怎么让主机不休眠
Mac Mini 的防止休眠设置,在首选项,显示器里. 显示器里找到高级按钮. 然后有个开关是:显示器关闭时,防止自动进入睡眠.打开这个开关即可防止自动睡眠. Link:https://www.cnb ...
- [PHP] Laravel-admin 模型表格-列的显示-链接: 关联关系的跳转链接
link 将字段显示为一个链接. // link方法不传参数时,链接的`href`和`text`都是当前列的值 $grid->column('homepage')->link(); // ...
- 支持 dotnet 6 的 dnSpy 神器版本
官方的 dnSpy 在 2021 时,由于某些吃瓜的原因 wtfsck 将 dnSpy 给 Archived 掉,在大佬被哄好之前,预计是不再更新.最新官方版本对 dotnet 6 的支持较弱,对于很 ...
- 2019-10-7-WPF-will-break-when-an-exception-be-throw-in-the-StylusPlugIn
title author date CreateTime categories WPF will break when an exception be throw in the StylusPlugI ...
- 如何在M1 MACBOOK上准备好ORB-SLAM2的环境
1. 环境 M1 Macbook Air Parallels Desktop 17 关于虚拟机,在之前尝试了UTM,但是性能欠佳,卡顿情况比较多,而且未能解决联网问题,最终只能含泪放弃 Paralle ...
- 一键关闭 Win11 系统广告「GitHub 热点速览」
不知道读者中有多少人早已对 Windows 11 系统自带的广告感到厌烦,却又不知道如何关闭它们? 虽然网上有详细的关闭教程,但是都需要逐一手动操作,不是很方便.所以,今天「GitHub 热点速览」给 ...
- ASP.NET Core的全局拦截器(在页面回发时,如果判断当前请求不合法,不执行OnPost处理器)
ASP.NET Core RazorPages中,我们可以在页面模型基类中重载OnPageHandlerExecuting方法. 下面的例子中,BaseModel继承自 PageModel,是所有页面 ...
- java学习之旅(day.19)
多线程 线程简介 多任务:同时做多件事 进程(Process):在操作系统中运行的程序就是进程,如QQ,播放器,游戏. 线程(Thread):一个进程可以有多个线程,如视频中同时听声音,看弹幕,看图像 ...
- kubernetes 之Health Check 健康检查
默认的健康检查 这里Pod的restartPolicy设置为OnFailure,默认为Always. [machangwei@mcwk8s-master ~]$ cat mcwHealthcheck. ...
- layui表格内可编辑下拉框
表格内可编辑下拉框扩展自别人的表格内下拉框 一.列模板,这是列配置的templet字段需要使用的. 1.inputdiv,输入框覆盖在下拉框上面左半部.这个样式用来调整输入框和下拉框不会超出单元格. ...