如何将JSON对象转换为servlet?
基本上我有我创建一个JSON对象的HTML文件:如何将JSON对象转换为servlet?
function CreateJson() {
var tableObj = [];
var loopCounter = 0;
var inputValues = [];
var table = document.getElementById('inputTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
loopCounter++;
inputValues.push(table.rows[r].cells[c].firstChild.value);
if (loopCounter == 3) {
tableObj.push({
model : inputValues[0],
colour : inputValues[1],
year : inputValues[2]
});
loopCounter = 0;
inputValues = [];
}
}
}
$.ajax({
type : 'POST',
dataType : 'json',
data: { tableObj : JSON.stringify(jsondata)},
url : 'ServletUrl',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
}
我有一个action
我的Java servlet形式,当我提交表单,JavaScript代码上面得到执行。如何检索和解析我的servlet中的JSON对象? JSON对象是tableObj
。
编辑: 我编辑CreateJson功能:
,在我的servlet我有:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Object json = request.getParameter("tableObj");
System.out.println(json);
在它打印空的日志。
查看正在使用POST在您的Java脚本
$.ajax({
type : 'POST',
dataType : 'json',
data: { tableObj : JSON.stringify(jsondata)},
url : 'ServletUrl',
timeout : 5000,
success : function(data, textStatus) {
// whatever
},
error : function(xhr, textStatus, errorThrown) {
// whatever
}
});
,但使用的是不相同的动词(的doPost)在servlet,请更改
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
到
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
您无法在Servlet实现中将doGet()更改为doPost()。你必须声明两种方法。 –
我想说的是,嗨读的是doGet中的值,而不是他必须在doPost中读取它,而且你是正确的两种方法都属于同一个接口... –
我将其更改为键入:'GET ',但我的doGet函数仍然返回null。 –
我不理解你的 题。 TableObj是一个json对象?你想在servlet中获得它吗?你发送它? –
如何发送tableObj到servlet。我想在我的servlet中使用tableObj –
您是否尝试将它发布到servlet,例如使用jquery? http://api.jquery.com/jquery.post/ –