jquery与后台进行数据交互--前台发单一数据对象,后台返回一个json字符串 serlet

package test;


import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




public class JquerySerlet extends HttpServlet
{
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{


String action=request.getParameter("action");

if("test".equals(action))
{
this.testParJson(request,response); 
}
}



 private void testParJson(HttpServletRequest request, HttpServletResponse response) 

{

response.setContentType("text/html;charset=UTF-8");  //注意编码方式应该与请求时一致

/**  方式一:前端发送来单个数据形式 返回一个json对象*/
/* String name=request.getParameter("name");
String pwd=request.getParameter("pwd");
System.out.println("copy name:"+name+":pwd:"+pwd);
PrintWriter pw=null;
JSONObject obj=null;
try 
{
pw = response.getWriter();

obj=new JSONObject();
obj.put("name", "刘蒙尘");
obj.put("sex", "男");
obj.put("age", "26");
 

catch (IOException e) 
{

e.printStackTrace();
} catch (JSONException e) 
{

e.printStackTrace();
}
         pw.write(obj.toString());
pw.flush();
pw.close();
*/

/**方式二:解析前端发来的json对象*/
String data = request.getParameter("data"); //打断点查看发送过来的数据形式,可能是json数组形式
JSONObject jsonObject=null;
PrintWriter pw=null;
JSONObject obj=null;
try 
       {  
 
jsonObject=new JSONObject(data);
String name=jsonObject.getString("name");
        String age=jsonObject.getString("age");
        String sex=jsonObject.getString("sex");
        System.out.println("测试解析的json字符串:"+name+":"+age+":"+sex);


       


        pw = response.getWriter();

obj=new JSONObject();
obj.put("name", "刘蒙尘");
obj.put("sex", "男");
obj.put("age", "26");
       }
 
catch (IOException e) 
{

e.printStackTrace();
} catch (JSONException e) 
{

e.printStackTrace();
}
    String str="123";
               pw.write(str);           //这里不宜直接写字符串内容
pw.flush();
pw.close();
 
}


 
@Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException,
           IOException {
       processRequest(request, response);
   }


   @Override
   protected void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException,
           IOException {
       processRequest(request, response);
   }


   @Override
   public String getServletInfo()
   {
       return "Short description";
   }//


  
}






你可能感兴趣的:(移动web设计)