经过HttpServletRequest转换得到json对象

如何把前端传过来的Json对象解析出来?在java web应用中,咱们如何获取post请求body中的内容?
一般利用request获取参数能够直接经过req.getParameter(name)的方式获取url上面或者ajax data提交上来的参数。可是body是没有名字的,没法经过参数名字这种方式获取。这时候须要用到io流的方式来获取body中的内容。前端

package com.example.controller;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.alibaba.fastjson.JSONObject;
 
@RestController
@EnableAutoConfiguration
public class Example {
 
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }
    
    
    // 这里我没作异常处理
    @RequestMapping("/request")
    String request(HttpServletRequest request, HttpServletResponse response) {
        String param= null; 
        try {
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            System.out.println(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }
    
    
    
    
 
    @RequestMapping("/hello/{myName}")
    String index(@PathVariable String myName) {
        return "Hello " + myName + "!!!";
    }
}

 

获取body参数,须要在request.getParameter()方法以前调用(若是有须要取QueryString参数的话),由于一旦调用了getParameter()方法以后,再经过IO流的方式获取body参数就失效了(亲测返回"")java

 

参考:web

一、http://blog.techbeta.me/2015/12/java-http-json/ajax

二、https://blog.csdn.net/qq_27292113/article/details/76837603spring

相关文章
相关标签/搜索