• SpringBoot自定义注解接收json参数


    SpringBoot如果接受json参数的话需要定义实体类然后使用@RequestBody注解,但是如果每个接口都创建一个实体类的话太麻烦,因此可以使用自定义注解的方法接收。从网上发现了这篇博客,解决了一个大大的疑惑。。转载: 大佬的博客

    1. RequestJson
    package com.school.service.config;
    
    import java.lang.annotation.*;
    
    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface RequestJson {
        /**
         * 值
         */
        String value() default "";
    
        /**
         * 是否必须
         */
        boolean require() default false;
    }
    
    
    1. RequestJsonHandlerMethodArgumentResolver
    package com.school.service.config;
    
    import com.alibaba.fastjson.JSONObject;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.IOUtils;
    import org.springframework.core.MethodParameter;
    import org.springframework.web.bind.support.WebDataBinderFactory;
    import org.springframework.web.context.request.NativeWebRequest;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.method.support.ModelAndViewContainer;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.lang.reflect.Constructor;
    import java.rmi.ServerException;
    
    @Slf4j
    public class RequestJsonHandlerMethodArgumentResolver  implements HandlerMethodArgumentResolver {
    
        /**
         * key
         */
        private static final String JSON_BODY_KEY = "JSON_BODY_KEY";
    
        @Override
        public boolean supportsParameter(MethodParameter parameter) {
            return parameter.hasParameterAnnotation(RequestJson.class);
        }
    
        @Override
        public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    
            // 获取jsonNode
            JsonNode jsonNode = getJsonBody(webRequest);
    
            RequestJson requestSingleParam = parameter.getParameterAnnotation(RequestJson.class);
            // 名
            String value = determineParamName(parameter, requestSingleParam);
            // 结果
            JsonNode paramValue = jsonNode.get(value);
            // 是否必须
            boolean require = requestSingleParam.require();
            if (paramValue == null && require) {
                throw new ServerException("parameter[" + value + "]不能为空。");
            }
    
            if (paramValue == null) {
                return null;
            }
            Class<?> parameterType = parameter.getParameterType();
            Constructor<?> constructor = parameterType.getConstructor(String.class);
            Object param = null;
            try {
                param = constructor.newInstance(paramValue.asText());
            } catch (Exception e) {
                log.error("bind method parameters error", e);
                throw new ServerException("parameter[" + value + "] format error for input value[" + paramValue.toString() + "]");
            }
            return param;
        }
    
        private String determineParamName(MethodParameter parameter, RequestJson requestSingleParam) {
            String value = requestSingleParam.value();
            if (value == null  || value.isEmpty()) {
                value = parameter.getParameterName();
            }
            return value;
        }
    
        private JsonNode getJsonBody(NativeWebRequest webRequest) throws JsonProcessingException {
    
            // 有就直接获取
            String jsonBody = (String) webRequest.getAttribute(JSON_BODY_KEY, NativeWebRequest.SCOPE_REQUEST);
            // 没有就从请求中读取
            if (jsonBody == null) {
                try {
                    HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
                    jsonBody = IOUtils.toString(servletRequest.getReader());
                    webRequest.setAttribute(JSON_BODY_KEY, jsonBody, NativeWebRequest.SCOPE_REQUEST);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return new ObjectMapper().readTree(jsonBody);
        }
    }
    
    
    1. 配置config
    package com.school.service.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.method.support.HandlerMethodArgumentResolver;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import java.io.File;
    import java.util.List;
    
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
            resolvers.add(new RequestJsonHandlerMethodArgumentResolver());
            WebMvcConfigurer.super.addArgumentResolvers(resolvers);
        }
    }
    
    
    1. 使用
    public Result register(@RequestJson String userCode, @RequestJson String nickName, @RequestJson String password) {
    

    成功

  • 相关阅读:
    Ubuntu 16.04 安装 Wireshark分析tcpdump的pcap包——sudo apt install wireshark-qt
    tcpdump dns流量监控
    ubuntu dig timeout解决方法,dnscat执行失败也是这个原因
    dns tunnel C&C
    “借贷宝”到底是不是坑?——“借贷宝”注册送现金营销模式分析?【已亲测可以无条件提现成功】
    借贷宝注册提现详细攻略:注册送20元,邀请好友再各送20元,亲测可无条件提现(附提现、到账截图)
    滴滴专车司机苹果手机ios客户端可以下载了
    优步UBER司机全国各地奖励政策汇总:北京、上海、广州、深圳、佛山、天津、南京、武汉、成都、重庆、济南、西安、宁波、青岛、长沙、苏州
    北京优步UBER司机B组最新奖励政策、高峰翻倍奖励、行程奖励、金牌司机奖励【每周更新】
    优步UBER司机奖励政策:含高峰、翻倍、行程、金牌司机、保底奖励(持续更新...)
  • 原文地址:https://www.cnblogs.com/charlottepl/p/15594115.html
Copyright © 2020-2023  润新知