字符串string = request.getParameter("data")为null [英] String string = request.getParameter("data") is null

查看:354
本文介绍了字符串string = request.getParameter("data")为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Servlet,它将接受来自AJAX请求的POST数据.

I am writing a servlet that will accept POST data coming from an AJAX request.

这是我从客户端发送的代码:

Here is the code I send from the client:

$.ajax({
            type: "POST",
            url: "urlservlet",
            data: "{type:'" + "country" + 
            "', country:'" + $('#country').val() +
            "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {

            }


这是servlet代码:


And this is the servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
    string test = request.getParameter("type");
}

但是事情是我总是得到等于null的类型.我不知道为什么.

But the thing is I always get the type equal to null. I don't know why.

请帮助我.

推荐答案

您正在将JSON写入请求主体并需要请求参数.来自 javadoc :

You are writing JSON to your request body and expecting request parameters. From the javadoc:

以String的形式返回请求参数的值;如果 参数不存在.请求参数是额外的信息 与请求一起发送. 对于HTTP Servlet,参数包含在 查询字符串或发布的表单数据.

Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

您尚未发布表单数据,也没有查询字符串.

You haven't posted form data and don't have a query string.

您想要的是使用HtppServletRequest#getInputStream()读取HTTP请求正文并解析JSON以提取您的元素.

What you want is to read the HTTP request body with HtppServletRequest#getInputStream() and parse the JSON to extract your element.

这篇关于字符串string = request.getParameter("data")为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆