`

j2ee22:json

    博客分类:
  • j2ee
 
阅读更多

第一:概念

1.json数据格式:是js的一种数据格式
2.json用来保存数据和传输数据(java和js都支持json格式,因此json就是在java和js之间传值)
3.json跟xml一样有固定的格式。以键值对的方式保存值:var json={"kw1":"kv1","kw2":"kv2","kw3":"kv3"}。这里就是一个集合。键相当于类中的属性,值相当于属性的值
4.对json进行遍历(因为json是集合,eval是js中的一个全局的方法):alert(eval(json)),这里是强制转换
5.{"kw1":"kv1"}["kw1"]:表示在{"kw1":"kv1"}这个json对象中通过键kw1取值kv1
6.json对象可以理解成实体类的对象
7.eval(参数是json类型的字符串):就是将从action取到的字符串转化成json对象,因此action中的字符串要写成json格式的。eval是javascript中的一个全局方法
注意:在ajax的responseText方法中接收的值是个字符串,而javascript中的json是个集合,因此使用eval,eval是将字符串转化成字符串数组,强转。
注:eval是将字符串转化成数组,而这个数组中的每个元素却是一个json数据格式的字符串,因此就达到了将java代码中的action层的字符串传到js中并以json的格式显示。
8.json-lib包调用了前面几个包的方法,因此要使用json-lib包就要把前面几个包也导入
9.把代码封装成一个方法,传入的是集合返回的是json对象。
注意:{"kw1":"kv1"}是一个json对象,我们把多个json对象放在集合中var json=[{"kw1":"kv1"},{"kw1":"kv1"},{"kw1":"kv1"}]
其中:var arr=[]是javascript中数组的创建方式。

10.post提交方式在发送send()之前要写xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//发送请求之前要写这句话

-----------------------
注意键盘事件:onkey...
onkeyup事件是当键盘弹起来的时候
onkeypress事件是当键盘按下去的时候
onkeydown事件也是键盘按下去的时候
鼠标事件:
鼠标放上去(滑过)的时候:onmouseover
鼠标离开的时候onmouseout

onblur:失去焦点
onfocus:获得焦点
onchange:内容改变的时候触发,常用于slelect中
onclick单击事件


---------------
重点1:用户在填写input标签的时候就随时产生下拉列表的思路:
1.早dao层写一个sql查询方法,注意是模糊查询:select userName from userInfo where  userName like '"+uname+"%'"
2.在action层遍历查询结果的时候把查询结果转化成StringBuffer 并用逗号隔开for(Users u:ulist){sb.append(u.getUname()+",");}
3.jsp上把StringBuffer转化成数组变量。
4.在input标签的地方加上onkeyup事件
注意:servive层是业务层,进行逻辑判断
-------------------
重点2:json对象在项目中使用的过程:
JSONArray是个静态的类,直接类名调用,参数是任意类型的(我们通常是传入一个集合),返回值是JSONArray对象,这个对象里面的内容就是json格式的,然后回调函数使用responseText接收这个数据,
responesText接收的数据都是字符串,因此使用eval转化成集合(这些字符串又符合javascript中的json的数据格式+现在这些字符串又强转成是集合了=此时这些内容就是javascript中的json对象了),有了json对象,
就能使用json的语法结构了:myjson[x]["uname"]。

 

第二:使用json完成用户名的搜索

1.action层

package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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 com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.entity.UserInfo;

public class UserAction extends HttpServlet{

 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  String uname=req.getParameter("uname");
  UserInfoDao udao=new UserInfoDaoImpl();
  List<UserInfo> userlist=udao.findAll(uname+"%");//通过姓名找学生(通过关键字找学生)
  PrintWriter out=resp.getWriter();
     JSONArray json=JSONArray.fromObject(userlist);//静态方法类名调用,传入一个object类型的数据,返回一个jsonArray类型的(符合javascript中的json对象的书写格式)。也就是json数组
     System.out.println(json.toString());
  out.write(json.toString());//write里面要写入一个字符串
 }
 

}

2.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
      function createrXmlHttpRequest(){
        if(window.ActiveXObject){
         return new ActiveXObject("Microsoft.XMLHTTP");        
        }else{
         return new XMLHttpRequest();
        }
      }
      var xhr;
      var d=new Date();
      function isExists(){//检查用户名的
       //alert("进入ajax");
       var uname=document.myform.uname.value;
          xhr=createrXmlHttpRequest();
          xhr.open("post","userAction");
          xhr.onreadystatechange=callback;
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//发送请求之前要写这句话
          xhr.send("uname="+uname); 
      }
      function callback(){
       if(xhr.readyState==4&&xhr.status==200) {
       
        var mydiv=document.getElementById("message");
        var res=xhr.responseText;//接收服务器端的响应结果。注意这个结果是个字符串
       // alert(res);//这里是个字符串
        var myjson=eval(res);//将接收到的字符串转化成数组
        //alert(myjson);//这是是个json数据格式的集合
        mydiv.innerHTML="";//由于是循环,因此每输入一个数都会有一次响应结果,这里是把上一次的响应结果清空,从而接收这次的响应。
        for(var x=0;x<myjson.length;x++){
         var username=myjson[x]["uname"];
         var div=document.createElement("div");
         div.onmouseover=changeColor;//鼠标划过的时候给个颜色
      div.onmouseout=changeColor2;//鼠标离开的时候变成白色
      div.onclick=changeTxt;//点击的时候给文本框赋值
         var txt=document.createTextNode(username);
         div.appendChild(txt);
         mydiv.appendChild(div);

        }
       }
      }
     
     
      function changeColor(){//改变颜色并把值显示在文本框上面
       this.style.backgroundColor="blue"; //改变颜色,鼠标划过的时候的颜色
      
      }
      function changeColor2(){
       this.style.backgroundColor="white";//鼠标离开的时候变成白色
      }
      function changeTxt(){//给文本框赋值
       var res=xhr.responseText;
          if(res.length!=0){
         document.getElementById("uname").value= this.innerHTML;//赋值。把当前选择的内容的值当做文本框里的值;
           }
          isExists();
      }
    
 </script>
  </head>
 
  <body>
     <form action="" name="myform" method="post">
                          <h3>搜索用户名</h3> 
                <input type="text" name="uname" id="u" onkeyup="isExists()">
                <div id="message"></div>
            <%--<input type="button" value="提交" onclick="isExists()">               
     --%></form>
    
  </body>
</html>

第三:ajax技术完成用户名唯一性验证

1.action层

package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

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

import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.entity.UserInfo;

public class UserAction extends HttpServlet {

 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setContentType("text/html;charset=UTF-8");
  String uname=req.getParameter("uname");
  System.out.println("输出姓名:"+uname);
  //uname=URLDecoder.decode(URLEncoder.encode(uname,"ISO-8859-1"),"UTF-8");
  System.out.println("输出姓名:"+uname);
  UserInfoDao udao=new UserInfoDaoImpl();
  UserInfo user=udao.SearchOne(uname);
  PrintWriter out=resp.getWriter();
  if(user!=null){
   out.print("用户名以被占用....");
  }else{
   out.print("用户名可用...");
  }
  
 }
 
 

}

2.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
      function createXmlHttpRequset(){
       if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");
       }else{
        return new XMLHttpRequest();
       }
      }
      var xhr;
      function sendRequest(){
      // alert(333);
       xhr=createXmlHttpRequset();//1.获得对象
       xhr.open("post","userAction",true);//2.准备发送
       xhr.onreadystatechange=callback;//3.回调函数,也就是监听状态码
       var uname=document.getElementById("username").value;
       alert("输出:"+uname);
       xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
       xhr.send("uname="+uname); //发送
      }
      function callback(){
       if(xhr.readyState==4&&xhr.status==200){
        var span=document.getElementById("span");
        var res=xhr.responseText;
        span.innerHTML=res;
       }
      }
   
 </script>

  </head>
 
  <body>
                 用户名:<input type="text" id="username"  onblur="sendRequest()"/><span id="span"></span>
          <input type="button" value="提交" onclick="sendRequest()"/>
  </body>
</html>

第四:股票:其实就是分页显示,但是使用ajax+json,并且是自动分页

1.action层

package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import net.sf.json.JSONArray;

import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.entity.UserInfo;

public class GupiaoAction extends HttpServlet{

 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setContentType("text/html;charset=UTF-8");
  UserInfoDao udao=new UserInfoDaoImpl();
  HttpSession session=req.getSession();
  /*List<UserInfo> ulist=udao.findAll();
  JSONArray json=JSONArray.fromObject(ulist);
  System.out.println(json);
  PrintWriter out=resp.getWriter();
  out.print(json);*/
  
  int pageNum=1;
  int pageSize=3;
  int num=udao.getFinalPage(pageSize);
  System.out.println("总页数:"+num);
  Object obj =session.getAttribute("pn");
  if(obj==null){
    pageNum=1;
  }else{
   pageNum=(Integer) obj;
   if(pageNum==num){
    pageNum=1;
   }else{
    pageNum++;
   }   
  }
     System.out.println("当前页:"+pageNum);
  List<UserInfo> ulist=udao.Fenye(pageNum, pageSize);
  //pageNum++;
  
  session.setAttribute("pn", pageNum);
  JSONArray json=JSONArray.fromObject(ulist);
  System.out.println(json);
  PrintWriter out=resp.getWriter();
  out.print(json);
 }
 

}

2.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  function createrXmlHttpRequest(){
       if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");        
       }else{
        return new XMLHttpRequest();
       }
    }
 
      var xhr;
      //function sendRequest(){
     //  alert("eeee");
      // xhr=createrXmlHttpRequest();
      // xhr.open("post","gupiaoAction");
      // xhr.onreadystatechange=callback;
      // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      // xhr.send(null);
      
      
    //  }
     
      function sendRequest(){
       //alert("eeee");
       xhr=createrXmlHttpRequest();
       xhr.open("post","gupiaoAction");
       xhr.onreadystatechange=callback;
       xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
       xhr.send(null);
      }
     
      function callback(){
       if(xhr.readyState==4&&xhr.status==200) {
        var res=xhr.responseText;
        //alert(res);
        var myjson=eval(res);
        var table=document.getElementById("t");
        table.innerHTML="";
        for(var x=0;x<myjson.length;x++){
        
         var uuid=myjson[x]["uuid"];
         var uname=myjson[x]["uname"]
         var upwd=myjson[x]["upwd"];
         //alert(uuid+uname+upwd);
        
        // var tr=document.createElement("tr");
        // var td1=document.createElement("td");
         //var td2=document.createElement("td");
         //var td3=document.createElement("td");
         //var txt1=document.createTextNode(uuid);
         //var txt2=document.createTextNode(uname);
        // var txt3=document.createTextNode(upwd);
        
         //td1.appendChild(txt1);
        // td2.appendChild(txt2);
         //td3.appendChild(txt3);
         //tr.appendChild(td1);
         //tr.appendChild(td2);
        // tr.appendChild(td3);
         //table.appendChild(tr);
        var div= document.createElement("div");
        div.innerHTML=uuid+" "+uname+" "+upwd;
        table.appendChild(div);
        
        }
       
       }
      
      }
     
     
       
      function mystart(){
    window.setInterval("sendRequest()",2000);
   }
 
 
      
     
 </script>
 </head>
 
  <body onload="mystart()">
  <h3>动态刷新页面</h3>
 
    <%--<table id="t" border="2">
      <tr>
         <td>编号</td>
         <td>姓名</td>
         <td>密码</td>
       </tr>
   </table>--%>
   <div id="t"></div>
   <%--<input type="button" value="提交" onclick="sendRequest()" id="tj">--%>
   </body>
</html>

第五:json=:每个3秒输出销量最多的前三种信息

1.实体类

package com.entity;

public class Produce implements Comparable<Produce>{
 private int pid;
 private double price;
 private String pname;
 public int getPid() {
  return pid;
 }
 public void setPid(int pid) {
  this.pid = pid;
 }
 public double getPrice() {
  return price;
 }
 public void setPrice(double price) {
  this.price = price;
 }
 public String getPname() {
  return pname;
 }
 public void setPname(String pname) {
  this.pname = pname;
 }
 public Produce() {
  super();
  // TODO Auto-generated constructor stub
 }
 public Produce(int pid, double price, String pname) {
  super();
  this.pid = pid;
  this.price = price;
  this.pname = pname;
 }
 @Override
 public String toString() {
  return "Produce [pid=" + pid + ", price=" + price + ", pname=" + pname
    + "]";
 }
 @Override
 public int compareTo(Produce o) {
  if(this.price==o.price){
   return 0;
  }else if(this.price>o.price){
   return 1;
  }else{
      return -1;
     }
 }
 
 

}

2.action层

package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

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 com.entity.Produce;

public class ProduceAction extends HttpServlet{

 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  resp.setContentType("text/html;charset=UTF-8");
  Produce p1=new Produce(1,Math.random()*10+5,"香蕉");
  Produce p2=new Produce(2,Math.random()*10+5,"苹果");
  Produce p3=new Produce(3,Math.random()*10+5,"水蜜桃");
  Produce p4=new Produce(4,Math.random()*10+5,"西瓜");
  Produce p5=new Produce(5,Math.random()*10+5,"荔枝");
  Set prodset=new TreeSet();
  prodset.add(p1);
  prodset.add(p2);
  prodset.add(p3);
  prodset.add(p4);
  prodset.add(p5);
  List<Produce> plist =new ArrayList<Produce>();
  Iterator<Produce> it = prodset.iterator();
  while(it.hasNext()){
   plist.add(it.next());
  }
  JSONArray pjson=JSONArray.fromObject(plist);
  System.out.println(pjson);
  PrintWriter out=resp.getWriter();
  out.print(pjson);
  
 }
 /*public static void main(String[] args) {
  Produce p1=new Produce();
  p1.setPid(1);
  p1.setPname("香蕉");
  Random r=new Random();
  //int r1=r.nextInt(22)+5;//生成一个5到26的随机数,包括26
   double r2 = (Math.random()*10+5);//生成一个5到14的随机数
  p1.setPrice(r2);
  System.out.println(p1);
 }*/

 /*public static void main(String[] args) {
  
  Produce p1=new Produce(1,Math.random()*10+5,"香蕉");
  Produce p2=new Produce(2,Math.random()*10+5,"苹果");
  Produce p3=new Produce(3,Math.random()*10+5,"水蜜桃");
  Produce p4=new Produce(4,Math.random()*10+5,"西瓜");
  Produce p5=new Produce(5,Math.random()*10+5,"荔枝");
  Set prodset=new TreeSet();
  prodset.add(p1);
  prodset.add(p2);
  prodset.add(p3);
  prodset.add(p4);
  prodset.add(p5);
  List<Produce> plist =new ArrayList<Produce>();
  Iterator<Produce> it = prodset.iterator();//迭代器是时序排序的(从小到大的顺序)
  while(it.hasNext()){
   plist.add(it.next());
  }
  for(int x=0;x<plist.size();x++){
   System.out.println(plist.get(x));
  }
 }*/
 

}

3.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  function createrXmlHttpRequest(){
       if(window.ActiveXObject){
        return new ActiveXObject("Microsoft.XMLHTTP");        
       }else{
        return new XMLHttpRequest();
       }
    }
  var xhr;
  function sendRequest(){
     // alert("eeee");
      xhr=createrXmlHttpRequest();
      xhr.open("post","produceAction");
      xhr.onreadystatechange=callback;
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xhr.send(null);
     }
  function callback(){
      if(xhr.readyState==4&&xhr.status==200) {
      // alert("eeee");
       var res=xhr.responseText;
       var myjson=eval(res);
       //alert("输出结果:"+myjson);
       var mydiv=document.getElementById("mydiv");
       mydiv.innerHTML="";
       for(var x=myjson.length-1;x>=2;x--){
       
        var pid=myjson[x]["pid"];
        var pname=myjson[x]["pname"]
        var price=myjson[x]["price"];
        var div= document.createElement("div");
        div.innerHTML=pid+" "+pname+" "+price;
        mydiv.appendChild(div);  
      }
  } 
    }
  function mystart(){
   window.setInterval("sendRequest()",3000);
   }
  </script>
  </head>
 
  <body onload="mystart()">
      <div id="mydiv"></div>
  </body>
</html>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics