• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

springmvc @RequestBody String类型参数的使用

java 搞代码 4年前 (2022-01-09) 27次浏览 已收录 0个评论
文章目录[隐藏]

springmvc @RequestBody String类型参数

通过如下配置:

   <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/>
                <!-- JSON转换器 -->
            </list>
        </property>
    </bean> 

在spring mvc的Controller层使用@RequestBody接收Content-Type为application/json的数据时,默认支持Map方式和对象方式参数

@RequestMapping(value = "/[code]/saveUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult saveUser(@PathVariable("code") Integer code, @RequestBody Map<String, Object> datas,@RequestBody User user) {
    。。。
    }

如果是一个参数时也需要用个Map或者对象处理,使用String会报解析错误,具体看:AbstractJackson2HttpMessageConverter的方法read(Type type, Class

@Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        JavaType javaType = getJavaType(type, contextClass);
        return readJavaType(javaType, inputMessage);
    }
    private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
        try {
            return this.objectMapper.readValue(inputMessage.getBody(), javaType);
        }
        catch (IOException ex) {
            throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
        }
    }

为了让@RequestBody支持String参数(目前只支持接收单个参数)

重写org.springframework.http.converter.json.MappingJackson2HttpMessageConverter类

package com.test.converter.json
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
/**
 * 处理@RequestBody注解为String的情况,只支持接收单个参数的情况
 * Created by test
 * Date:2017/1/4
 * Time:17:33
 */
public class CustomerMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    @Override
    protected <span>本文来源gaodai#ma#com搞*代#码9网#</span>Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        Class<?> deseriClazz = getClazz(clazz);
        Object param = super.readInternal(deseriClazz, inputMessage);
        return getTrueObject(clazz, param);
    }
    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        Type deseriType = getType(type);
        Object param = super.read(deseriType, contextClass, inputMessage);
        return getTrueObject(type, param);
    }
    /**
     * 通过返回参数类型决定是否处理参数,如果是String类型的参数,将解析后的HashMap里的值返回(只支持单个参数)
     *
     * @param type  返回参数类型
     * @param param 参数值
     * @return 实际参数值
     */
    private Object getTrueObject(Type type, Object param) {
        if (type == String.class) {
            Object backParam = null;
            if (param != null && param instanceof LinkedHashMap) {
                LinkedHashMap paramMap = (LinkedHashMap) param;
                if (paramMap.size() == 1) {
                    backParam = paramMap.get(paramMap.keySet().iterator().next());
                }
            }
            param = backParam;
        }
        return param;
    }
    /**
     * 获取解析参数用的Type
     *
     * @param type 参数类型
     * @return
     */
    private Type getType(Type type) {
        Type deseriClazz;
        if (type == String.class) {
            //jackson不支持String默认用LinkedHashMap
            deseriClazz = LinkedHashMap.class;
        } else {
            deseriClazz = type;
        }
        return deseriClazz;
    }
    /**
     * 获取解析参数用的Type
     * @param clazz 参数类型
     * @return
     */
    private Class<?> getClazz(Class<?> clazz) {
        Class<?> deseriClazz;
        if (clazz == String.class) {
            //jackson不支持String默认用LinkedHashMap
            deseriClazz = LinkedHashMap.class;
        } else {
            deseriClazz = clazz;
        }
        return deseriClazz;
    }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springmvc @RequestBody String类型参数的使用
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址