spring mvc @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 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;
    }
}

spring mvc xml配置文件修改:

<bean id="mappingJacksonHttpMessageConverter"
          class="com.test.converter.json.CustomerMappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>

Controller層:

@RequestMapping(value = "/delUser", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delUser(@RequestBody String id) {
    。。。
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章