servlet向ajax传递list数据类型,ajax向servlet传递array数据类型

时间:2024-04-15 12:18:54

因工作需要,

1,后台向前台传递一个list

2,前台向后台传递类似于list的结构,但是因为javascript不支持list类型,所以只能使用二维数组代替

后台运行后的截图:                                                                前台运行后的截图:               

                                                   

后台代码(TestJson.java)

package com.zm.servlet;  
  
import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.ArrayList;  
import java.util.HashMap;
import java.util.List;  
import java.util.Map;
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import net.sf.json.JSONArray;  
import net.sf.json.JSONObject;
  
public class TestJson extends HttpServlet {  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
           doPost(request,response);  
    }  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        
        System.out.println("into doPost");
        
        response.setContentType("text/html");     
        String sName= request.getParameter("name");//得到ajax传递过来的paramater  
        System.out.println(sName);
        
        //String sTicketId= request.getParameter("ticketId");//得到ajax传递过来的paramater  
        //System.out.println(sTicketId);

        try {  
            String[] sTicketIds = request.getParameterValues("ticketId[]");        
            if(sTicketIds !=null){  
                for(String sTicketId:sTicketIds){  
                    System.out.println(sTicketId);  
                }  
            }else{  
                System.out.println("获取数组参数失败!");  
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        }  

        PrintWriter printWriter = response.getWriter();  
        List list = new ArrayList();//传递List  
        
        Map m=new HashMap();//传递Map      
        User u1=new User();  
        u1.setUsername("zah");  
        u1.setPassword("123");  
        User u2=new User();  
        u2.setUsername("ztf");  
        u2.setPassword("456");    
        list.add(u1); //添加User对象        
        list.add(u2);     //添加User对象    
        
        m.put("u1", u1);  
        m.put("u2", u2);     
          
        JSONArray jsonArray2 = JSONArray.fromObject( list );  
        //把java数组转化成转化成json对象   
        //JSONObject jsonObject =JSONObject.fromObject(m);//转化Map对象  
        printWriter.print(jsonArray2);//返给ajax请求  
        //printWriter.print(jsonObject);//返给ajax请求  
        printWriter.flush();
        printWriter.close();
        System.out.println("finish");
    }  
}    

 

前台代码(first.jsp)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>   
    <script type="text/javascript" src="jQuery/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">  
       function test2(){  
          var ticketId = new Array();
          for(var i = 0; i < 5; i++) {
              ticketId.push(i);
          }
           $.ajax({
                type:"POST", //请求方式  
                url:"./testJson", //请求路径  
                cache: false,     
                data:{//传参  
                    "name":"zhang3",
                    "ticketId":ticketId,    
                },
                dataType: \'json\',   //返回值类型  
                success:function(json){        
                    alert(json[0].username+" " + json[0].password);    //弹出返回过来的List对象  
                    alert(json[1].username+" " + json[1].password);    //弹出返回过来的List对象
                }  
            });  
      }  
    </script>  
  </head>  
    
  <body>  
    <input type="button" name="b" value="TestJson" onclick="test2()"/>
    <input type="button" value="download file" onclick="DownURL(\'333.js\',\'d:/555.js\')"/>
  </body>  

</html>

web.xml

    <!-- 测试jquery json-->
    <servlet>  
    <servlet-name>testJson</servlet-name>  
    <servlet-class>com.zm.servlet.TestJson</servlet-class>  
  </servlet>  
   <servlet-mapping>  
    <servlet-name>testJson</servlet-name>  
    <url-pattern>/testJson</url-pattern>  
  </servlet-mapping>