当前位置 : 主页 > 网页制作 > Nodejs >

webService 接受提交的JSon数据

来源:互联网 收集:自由互联 发布时间:2021-06-24
1、controller @RequestMapping(value = "saveJson")@ResponseBodypublic Map saveJson(HttpServletRequest request) throws IOException {Map map = new HashMapString,Object();String submitMethod = request.getMethod();String data;if (submitMethod.e

1、controller

@RequestMapping(value = "saveJson")
@ResponseBody
public Map saveJson(HttpServletRequest request) throws IOException {
		Map map = new HashMap<String,Object>();
		String submitMethod = request.getMethod();
		String data;
		if (submitMethod.equals("GET")) {
			data= new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
		} else {
			data= getRequestPostStr(request);
		}
                map.put("data",data);
                return map;
}
2、工具类

package com.thinkgem.jeesite.modules.util;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by boxiaotong on 2017/1/17.
 */
public class RequestUtil {

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */

    public static String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }
    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例:
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }
}
网友评论