Ajax 介绍三

Ajax 介绍三

1.利用Ajax+JSON技术实现产品热销列表
JSP页面:
<%@ page language="java" import= "java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head >
    <title >Product </title>
    <script type="text/javascript">
     function getXMLHttpRequest()
     {
           if(window.XMLHttpRequest)
          {
               return new XMLHttpRequest(); 
          }
           else
          {
               return new ActiveXObject("Microsoft.XMLHTTP" );
          }
     }
     //加载热销排行榜信息
     function loadHotsale()
     {
           var xhr = getXMLHttpRequest();
          alert(xhr);
           var url = "hotsale.do?size=2" ;
          xhr.open( "GET",url);
          xhr.onreadystatechange = function()
          {
               var li = document.getElementById("s1" );
               var str = "" ;
               if(xhr.readyState == 4&&xhr.status==200)
              {
                    var txt = xhr.responseText;
                    var arr = eval("(" +txt+")" );
                    //循环JSON数组
                    for(var i=0;i<arr.length;i++)
                   {
                        str += "<li>"+arr[i].name+" "+arr[i].qty+"</li>";
                        alert(str);
                   }
                   li.innerHTML = str;
              }
          };
          xhr.send( null);
     }
     setInterval("loadHotsale()", 1000);
    </script >
  </head >
  <body >
    <div >
           <ul>
               <li> 钓鱼岛最新进展 </li>
               <li> 钓鱼岛历史</li >
               <li> 钓鱼岛能否开战 </li>
           </ul>      
    </div >
    <div >
     <h3 >热销排行榜 </h3>
     <ol id="s1">
           <li> BMW 3000</ li>
           <li> Q7 3000</ li>
           <li> Q5 2300</ li>
     </ol >
    </div >
  </body >
</html>
  entity:
public class Sale
{
     private int id ;
     private String name;
     private int qty ;
     public int getId()
     {
           return id ;
     }
     public void setId(int id)
     {
           this.id = id;
     }
     public String getName()
     {
           return name ;
     }
     public void setName(String name)
     {
           this.name = name;
     }
     public int getQty()
     {
           return qty ;
     }
     public void setQty(int qty)
     {
           this.qty = qty;
     }
}
  dao:
public class SaleDAO
{
     public List<Sale> findHotSale( int size) throws Exception
     {
          String sql = "select * from t_sale order by qty desc limit 0,?";
          Connection con = null;
           try{
              con = DBUtil. getConnection();
              PreparedStatement stmt = con.prepareStatement(sql);
              stmt.setInt(1, size);
              stmt.executeQuery();
              ResultSet rs = stmt.getResultSet();
              List<Sale> list = new ArrayList<Sale>();
              
               while(rs.next())
              {
                   Sale s = new Sale();
                   s.setId(rs.getInt( "id"));
                   s.setName(rs.getString( "name"));
                   s.setQty(rs.getInt( "qty"));
                   list.add(s);
              }
               return list;
          }
           catch (Exception e) {
               return null ;
          }
           finally{
              DBUtil. close(con);
          }
     }
}
  servlet:
public class HotServlet extends HttpServlet
{
     public void service(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException
     {
          request.setCharacterEncoding( "utf-8");
          response.setContentType( "text/html;charset=utf-8");
          PrintWriter out = response.getWriter();

          String size = request.getParameter( "size");
          
          System. out.println(size);
          
           int i = 3;
           if (size != null & !"".equals(size)) {
              i = Integer. parseInt(size);
          }
          SaleDAO dao = new SaleDAO();
           try {
               //查询记录,将记录转换成JSON对象
              List<Sale> list = dao.findHotSale(i);
              JSONArray jsonArray = JSONArray.fromObject(list);
              out.print(jsonArray.toString());
          } catch (Exception e) {
              e.printStackTrace();
          }
          out.flush();
          out.close();
     }
}
  2.Ajax有什么优点
 1)在整个页面不刷新的情况下,局部更新.
 2)异步请求处理模式,可以不打断用户操作
 3)采用按需方式提交请求数据和获取响应数据
     同步模式:请求1-->响应1回调执行-->请求2
     异步模式: 请求1-->请求2-->响应1回调执行

3.利用JSON.jar自定义转换格式
   1)编写一个格式转换器,需要实现 JsonValueProcessor接口及方法
public class DateProcessor implements JsonValueProcessor
{
     String pattern = "yyyy-MM-dd";
     public void setPattern(String pattern)
     {
           this.pattern = pattern;
     }
     public Object processArrayValue(Object arg0, JsonConfig arg1)
     {
          SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
          String dt = dateFormat.format((Date)arg0);
           return dt;
     }
     public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2)
     {
          SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
          String dt = dateFormat.format((Date)arg1);
           return dt;
     }
}
  2)在使用JSONObject,JSONArray时
     a.先创建一个JsonConfig对象,将格式转换器给JsonConfig对象注册.
        config.registerJsonValueProcessor(Date.  class ,processor); 
     b.在调用JSONObject和JSONArray的fromObject方法时,将config对象指定
        JSONObject array = JSONObject.   fromObject (person,config);
public class TestPerson
{
     public static void main(String[] args)
     {
          Person person = new Person();
          person.setId(1);
          person.setName( "张三");
          person.setBirth( new Date());
          
          JsonConfig config = new JsonConfig();
          DateProcessor processor = new DateProcessor();
           //自定义转换格式
          processor.setPattern( "yyyy*MM*dd");
           //为config 指定特定类型采用哪种转换器
          config.registerJsonValueProcessor( Date.class,processor);
           //将config 对象应用到fromObject方法中
          JSONObject array = JSONObject.fromObject(person,config);          
          System. out.println(array.toString()); 
     }
}
 

你可能感兴趣的:(Ajax)