2014-02-15 69 views
0

我使用YUI從頁面向服務器發送json以及如何從servlet中的json獲取數據。我使用傑克遜庫2.4。謝謝!!!如何使用Jackson在http servlet中解析json?

var user = { 
        userName: username, 
        password: password, 
        customerId: customerId 
        }; 

      new Y.IO().send("http://localhost:7778/MyController", { 
       method: 'POST', 
       data: user 
      }); 

回答

0

實際上,當你做出這樣的

<html> 
<body> 
<script src="http://yui.yahooapis.com/3.14.1/build/yui/yui-min.js"></script> 
<script> 
var user = { 
     userName: 'x1', 
     password: 'y2', 
     customerId: 'z3' 
     }; 
YUI().use('io-form', function (Y) { 
    new Y.IO().send("http://localhost:8080/web/MyController", { 
     method: 'POST', 
     data: user 
    }); 
}); 

</script> 
</body> 
</html> 

請求你不發送JSON對象到servlet。相反,你要創建一個HTTP請求在您的JavaScript對象(這是在JSON格式表示)的每個屬性被作爲一個HTTP POST屬性,因此你可以檢索這樣

package mine; 

import java.io.IOException; 
import java.util.Map; 
import java.util.Map.Entry; 

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

/** 
* Servlet implementation class MyController 
*/ 
@WebServlet("/MyController") 
public class MyController extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    /** 
    * @see HttpServlet#HttpServlet() 
    */ 
    public MyController() { 
     super(); 
     // TODO Auto-generated constructor stub 
    } 

    /** 
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
    */ 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     Map<String, String[]> map = request.getParameterMap(); 
     for(Entry<String,String[]> entry:map.entrySet()){ 
      System.out.println(entry.getKey()); 
      System.out.println(entry.getValue()[0]); 
     } 
    } 

} 

其在這些值轉而打印此

userName 
x1 
password 
y2 
customerId 
z3 

,所以你不需要傑克遜解析您從網頁中獲取數據。

+0

您的回答很有幫助。非常感謝! –

相關問題