我試圖在不使用任何框架的情況下實現REST類型體系結構。所以我基本上是從我的客戶端調用一個正在執行doPost()
的JSP到提供服務的遠程服務器上。現在我能夠以JSON格式將數據從客戶端傳遞到服務器,但我不知道如何讀取響應。有人能幫我解決這個問題嗎?從JSP中的doPost()返回
客戶端:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
....
HttpPost httpPost = new HttpPost("http://localhost:8080/test/Login");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//Send post it as a "json_message" paramter.
postParameters.add(new BasicNameValuePair("json_message", jsonStringUserLogin));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse fidresponse = client.execute(httpPost);
....
....
}
服務器端:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsonStringUserLogin = (String)request.getParameter("json_message");
....
....
request.setAttribute("LoginResponse", "hello");
// Here I need to send some string back to the servlet which called. I am assuming
// that multiple clients will be calling this service and do not want to use
// RequestDispatcher as I need to specify the path of the servlet.
// I am looking for more like return method which I can access through
// "HttpResponse" object in the client.
}
我剛開始用servlet和希望通過自己實現一個REST服務。如果您有任何其他建議,請大家分享...謝謝你,
中的doPost
你問的是如何從請求中獲取json字符串或者如何反序列化json字符串? – 2012-07-20 11:20:44
我想知道如何從請求中獲取JSON字符串?...從遠程計算機上的另一個servlet中獲取... – Fox 2012-07-20 11:23:30
響應正文將包含您的json響應。從fidresponse中讀取響應主體。 (我還不確定我是否理解你的問題) – 2012-07-20 11:26:06