Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用ajax post将json从js发送到控制器_Java_Javascript_Ajax_Json - Fatal编程技术网

Java 使用ajax post将json从js发送到控制器

Java 使用ajax post将json从js发送到控制器,java,javascript,ajax,json,Java,Javascript,Ajax,Json,我无法将json对象从javascript发送到java控制器 Ajax: var xmlHttp = getXmlHttpRequestObject(); if(xmlHttp) { var jsonObj = JSON.stringify({"title": "Hello","id": 5 }); xmlHttp.open("POST","myController",true); xmlHttp.onreadystatechange = han

我无法将json对象从javascript发送到java控制器

Ajax

var xmlHttp = getXmlHttpRequestObject();
if(xmlHttp) {
        var jsonObj = JSON.stringify({"title": "Hello","id": 5 });
        xmlHttp.open("POST","myController",true);
        xmlHttp.onreadystatechange = handleServletPost;
        xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.send(jsonObj);
    }
function handleServletPost() {
    if (xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            alert(window.succes);
        }
    }
}
我在Java中尝试的内容:

public void process(
        final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext servletContext, final TemplateEngine templateEngine) 
        throws Exception {

     String jsonObj = request.getParameter("jsonObj");
}
它们都是空的

我试着阅读相关文章和多种发送数据的方式,但结果相同。我不知道如何使用jqueryforajax,所以我主要在寻找js解决方案


有人能告诉我我错过了什么吗?由于我花了大约三个小时试图弄清楚,要用POST请求发送JSON,您必须用
doPost
方法读取请求的正文。这里有一种方法:

protected void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
    StringWriter sw = new StringWriter();
    IOUtils.copy(hreq.getInputStream(), sw, "UTF-8");
    String json = sw.toString();
然后必须解析JSON。例如,可以使用

假设您有一个带有公共参数
id
title
的类,这将是

Gson gson = new GsonBuilder().create();
Thing thing = gson.fromJson(json, Thing.class);
int id = thing.id;
String title = thing.title;

当然,除了gson之外,还有其他解析JSON的解决方案,但您必须解析它。

我认为您将URL参数与请求体混淆了。要从请求中获取json字符串,您需要从
request.getReader()

中读取它,我已经找到了它

Json应按如下方式发送:

xmlHttp.send("jsonObj="+jsonObj);
而不是

xmlHttp.send(jsonObj);

为了将其作为参数接收。

当发送字符串而不是json对象时,我的确切方法起作用,所以为什么我需要实现doPost?(我添加了我正在使用的方法)