通过Java Servlet中的jquery ajax发送参数

gae*_*gae 3 java ajax jquery json servlets

我在网上搜索这个主题,但我无法得到一个有效的例子.我会被一个人给我一个帮助.

这是我测试的.

 $.ajax({
    url: 'GetJson',
    type: 'POST',        
    dataType: 'json',
    contentType: 'application/json',

    data: {id: 'idTest'},
    success: function(data) {
        console.log(data);
    }
});
Run Code Online (Sandbox Code Playgroud)

在塞维莱特

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String id = request.getParameter("id");
    String id2[] = request.getParameterValues("id");        
    String id3 = request.getHeader("id");

}
Run Code Online (Sandbox Code Playgroud)

我的一切都变得空洞了.

Avi*_*ral 10

我有同样的问题,getParameter("foo")在servlet中返回null.找到一个简单的解决方案,可能对这里的人有用.使用默认值

contentType='application/x-www-form-urlencoded; charset=UTF-8'
Run Code Online (Sandbox Code Playgroud)

或者把它留下来.这将使用参数中的数据自动编码请求.

希望这可以帮助...


Nik*_*los 5

排序答案是该数据隐藏在请求中InputStream.

以下servlet是如何使用它的演示(我在JBoss 7.1.1上运行它):

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="fooServlet", urlPatterns="/foo")
public class FooServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = req.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buf = new byte[32];
        int r=0;
        while( r >= 0 ) {
            r = is.read(buf);
            if( r >= 0 ) os.write(buf, 0, r);
        }
        String s = new String(os.toByteArray(), "UTF-8");
        String decoded = URLDecoder.decode(s, "UTF-8");
        System.err.println(">>>>>>>>>>>>> DECODED: " + decoded);

        System.err.println("================================");

        Enumeration<String> e = req.getParameterNames();
        while( e.hasMoreElements() ) {
            String ss = (String) e.nextElement();
            System.err.println("    >>>>>>>>> " + ss);
        }

        System.err.println("================================");

        Map<String,String> map = makeQueryMap(s);
        System.err.println(map);
        //////////////////////////////////////////////////////////////////
        //// HERE YOU CAN DO map.get("id") AND THE SENT VALUE WILL BE ////
        //// RETURNED AS EXPECTED WITH request.getParameter("id")     ////
        //////////////////////////////////////////////////////////////////

        System.err.println("================================");

        resp.setContentType("application/json; charset=UTF-8");
        resp.getWriter().println("{'result':true}");
    }

    // Based on code from: http://www.coderanch.com/t/383310/java/java/parse-url-query-string-parameter
    private static Map<String, String> makeQueryMap(String query) throws UnsupportedEncodingException {
        String[] params = query.split("&");
        Map<String, String> map = new HashMap<String, String>();
        for( String param : params ) {
            String[] split = param.split("=");
            map.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
        }
        return map;
    }
}
Run Code Online (Sandbox Code Playgroud)

随着请求:

$.post("foo",{id:5,name:"Nikos",address:{city:"Athens"}})
Run Code Online (Sandbox Code Playgroud)

输出是:

>>>>>>>>>>>>> DECODED: id=5&name=Nikos&address[city]=Athens
================================
================================
{address[city]=Athens, id=5, name=Nikos}
================================
Run Code Online (Sandbox Code Playgroud)

(注意:req.getParameterNames()不起作用.第4行打印的地图包含通常可以使用的所有数据request.getParameter().另请注意嵌套对象表示法,{address:{city:"Athens"}}address[city]=Athens)


与您的问题略有不同,但为了完整起见:

如果要使用服务器端JSON解析器,则应使用JSON.stringify以下数据:

$.post("foo",JSON.stringify({id:5,name:"Nikos",address:{city:"Athens"}}))
Run Code Online (Sandbox Code Playgroud)

在我看来,与服务器通信JSON的最佳方式是使用JAX-RS(或Spring等价物).它在现代服务器上很简单并且解决了这些问题.

  • 可怕的建议.用户只是在jQuery中完全错误.这个问题应该在jQuery方面解决**,而不是在Servlet方面**工作区**.OP应该只是将数据作为具有键值对的真实JSON对象发送,而不是作为JSON格式的字符串.使用正确的内容类型集(默认值),jQuery将自动处理它,这样request.getParameterXxx()将透明地继续工作. (2认同)