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

2024-10-09 10:06:00 浏览数 (3)

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

代码语言:javascript复制
@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();
    }
}

0 人点赞