简体   繁体   English

从Java servlet内部获取Ajax参数

[英]Getting Ajax parameter from inside Java servlet

my data: 我的数据:

var test = {cars : []};

var cars = []
cars.push({
    "name" : "Ford",
    "year" : "2000"
});

    cars.push({
    "name" : "Audi",
    "year" : "2002"
});

test.cars = cars;   

var json = JSON.stringify(test);

$.get('/myservlet/', json, function(data) { // also tried .getJSON , .post
            alert('Success');                               
})

In Java I get the "json" variable as parameter key, but no value. 在Java中,我将“ json”变量作为参数键,但是没有值。

public void doPost(...) // TRIED BOTH
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {           
    for(Object a : req.getParameterMap().keySet()) {
        System.out.println(a + " - " + req.getParameter((String)a));
    }
//prints out
{"cars":[{"name":"Ford","year":"30"},{"name":"Audi","year":"2002"}]} - 

This is unusable result, because the key is always changing, and is ridiculous to for-loop the params everytime. 这是不可用的结果,因为密钥总是在变化,并且每次循环循环参数都是荒谬的。 I need to have a specific key : req.getParameter("cars") 我需要一个特定的键: req.getParameter("cars")

Change it to: 更改为:

$.get('/myservlet/', 'cars='+ json, function(data) { // also tried .getJSON , .post
        alert('Success');                   

You shouldn't have stringified the JSON at all. 您根本不需要对JSON进行字符串化处理。 The whole JSON object test is supposed to be treated as the request parameter map. 整个JSON对象test应被视为请求参数映射。 Just pass the JSON object unmodified. 只需传递未修改的JSON对象即可。

$.get('/myservlet/', test, function(data) {
    // ...
});

This way it's available in the servlet as follows: 这样,它就可以在servlet中使用,如下所示:

for (int i = 0; i < Integer.MAX_VALUE; i++) {
    String name = request.getParameter("cars[" + i + "][name]");
    if (name == null) break;
    String year = request.getParameter("cars[" + i + "][year]");
    // ...
}

Update Your question could be possible duplicate of READ JSON String in servlet 更新您的问题可能是servlet中READ JSON String的重复项

Previous answer 先前的答案

I assume you are trying to post JSON to the servlet, if thats the case read on. 我假设您正在尝试将JSON发布到servlet,如果是这样的话。

You would have to check for request body instead of request parameter. 您将必须检查请求正文而不是请求参数。 Something like 就像是

BufferedReader buff = req.getReader();

Check if this works for you 检查是否适合您

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
  BufferedReader buff = req.getReader();
  char[] buf = new char[4 * 1024]; // 4 KB char buffer
  int len;
  while ((len = reader.read(buf, 0, buf.length)) != -1) {
   out.write(buf, 0, len);
  }
}

Note that I have checked the above code for syntax errors. 请注意,我已经检查了上述代码中的语法错误。 I hope you get the idea. 希望您能明白。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM