首页 > 其他分享 >RequestBodyAdvice和注解方式进行统一参数处理demo

RequestBodyAdvice和注解方式进行统一参数处理demo

时间:2022-10-11 16:11:25浏览次数:42  
标签:return String RequestBodyAdvice demo new 注解 import public name

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();
    }
}

 

标签:return,String,RequestBodyAdvice,demo,new,注解,import,public,name
From: https://www.cnblogs.com/oktokeep/p/16779573.html

相关文章

  • AspNetCore中 使用 Grpc 简单Demo
    为什么要用Grpc跨语言进行,调用服务,获取跨服务器调用等目前我的需要使用我的抓取端是go写的查询端用Net6写的导致很多时候我需要把一些临时数据写入到Redis在两......
  • 如何使用vuforiaSDK开发第一个AR demo应用
    1.IfyouareusingorplanningtousetheAndroidStudioIDE,herearesomenotesabouthowtoimportandbuildtheVuforiasamples:首先安装好环境:JDK,NDK,AndroidS......
  • Java自定义注解实现权限管理
    前言Github地址:​​​https://github.com/erlieStar/authority_example​​源码定义权限注解@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@int......
  • spring day02 xml开发总结以及注解开发总结
    第三方资源配置管理管理DataSource连接池对象【第一步】添加Druid连接池依赖<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><......
  • java spring 纯注解开发
     创建核心容器有两个方法如下图     获取Bean对象方法有三种     BeanFactory与FactoryBean区别    spring纯注解由哪些常见的 ......
  • Flink自定义Oracle的Source的Demo
    1.实体类@Data@Builder//创建对象@NoArgsConstructor//无参构造函数@AllArgsConstructor//有参构造函数publicclassOrderSink{privateintid;......
  • springboot注解大全
    1.@ConfigurationProperties与@EnableConfigurationProperties对比与区别  ......
  • @Lazy注解的使用
    @Lazy注解主要有两种用途:一是可以减少Spring的IOC容器启动时的加载时间。二是可以解决bean的循环依赖问题。@Lazy的简介@Lazy注解用于标识bean是否需要延迟加载。@T......
  • FlinkSQL的DataStream和Table互转的Demo
    1.构建UserLog对象@Data@Builder//创建对象@NoArgsConstructor//无参构造函数@AllArgsConstructor//有参构造函数publicclassUserLog{privateStr......
  • 【SSM】学习笔记(一)—— Spring 概念、Spring IoC、Spring Bean相关知识、依赖注入、
    原视频:https://www.bilibili.com/video/BV1Fi4y1S7ix?p=1P1~P27目录一、Spring概述1.1、Spring家族1.2、Spring发展史1.3、SpringFramework系统架构图1.4、......