我正在尝试将 JSON 数组从浏览器发送到 PUT 方法上的 Java Servlet。
我的ajax请求:
$.ajax({
url : "./manageShoppingCart",
data : {
jsonArray : JSON.stringify(itemsArray)
},
type : 'PUT',
contentType : 'application/json'
}).done(function(rsp) {
console.log("done" + rsp);
}).fail(function(err) {
console.log("fail" + err);
});
服务器上是(在 doPut 方法中):
String jsonArray = request.getParameter("jsonArray"); // this is null
// but if I read from request stream I get the data
ServletInputStream inputStream = request.getInputStream();
String string = convertStreamToString(inputStream);
System.out.println(string); // jsonArray=%5B%7B%22itemId%22%3A%228003%22%2C%22itemQuantity%22%3A%2210%22%7D%2C%7B%22itemId%22%3A%228004%22%2C%22itemQuantity%22%3A%222%22%7D%5D
有趣的是,如果更改方法并作为 POST 发送,我会正确获取参数。
我的猜测是 Tomcat 6 需要一些设置才能通过 PUT(url 编码..等)获取参数。
那么,我应该怎么做才能通过 PUT 方法正确发送 JSON 数组呢?
更新:我不确定这是否是正确的方法,但对我来说,我发现自己编写一个从消息到参数的转换器很容易:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletInputStream;
public class RequestsService {
public static String getDecodedMessage(ServletInputStream inputStream) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
String bodyMessageEncoded;
bodyMessageEncoded = bf.readLine();
String message = URLDecoder.decode(bodyMessageEncoded, "UTF-8");
return message;
}
public static String getParameter(String url, String paramName) throws ArrayIndexOutOfBoundsException {
Pattern pattern = Pattern.compile(paramName + "=[^&]*"); // regex for "paramName='anything unless is &'"
Matcher matcher = pattern.matcher(url);
matcher.find();
String value = matcher.group().split("=")[1];
return value;
}
public static String getParameterFromStream(ServletInputStream inputStream, String paramName) throws IOException {
String decodedMessage = getDecodedMessage(inputStream);
return getParameter(decodedMessage, paramName);
}
}