我正在将jQuery AJAX POST发布到Servlet,并且数据采用JSON字符串的形式。它已成功发布,但在Servlet端,我需要将这些键- 值对读入Session Object并将其存储。我尝试使用JSONObject类,但无法获取它。
这是代码段
$(function(){ $.ajax( { data: mydata, //mydata={"name":"abc","age":"21"} method:POST, url: ../MyServlet, success: function(response){alert(response); } });
在Servlet方面
public doPost(HTTPServletRequest req, HTTPServletResponse res) { HTTPSession session = new Session(false); JSONObject jObj = new JSONObject(); JSONObject newObj = jObj.getJSONObject(request.getParameter("mydata")); Enumeration eNames = newObj.keys(); //gets all the keys while(eNames.hasNextElement()) { // Here I need to retrieve the values of the JSON string // and add it to the session } }
您实际上并没有解析json。
JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json Iterator it = jObj.keys(); //gets all the keys while(it.hasNext()) { String key = it.next(); // get key Object o = jObj.get(key); // get value session.putValue(key, o); // store in session }