JSON+AJAX的应用

本文详细介绍了如何利用JSON数据格式和AJAX进行异步请求,包括JSON类对象的生成,如自定义对象、从MAP和JAVA集合中生成,以及与AJAX结合进行用户名判断的步骤,涉及数据库查询、Servlet处理和JSP响应。同时,还展示了使用JSON和AJAX实现省、市、区信息联动的全过程,涵盖数据库设计、页面交互和Servlet处理等环节。
摘要由CSDN通过智能技术生成

主要内容:

- JSON数据格式

- AJAX异步请求

- 利用JSON+AJAX进行用户名的判断

- 利用JSON+AJAX进行省、市、区信息联动

详细记录:
1 JSON数据格式
JS中的JSON
JAVA中的JSON:
引入JAR包:
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-httpclient-3.1.jar
commons-lang-2.5.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar
json-lib-2.1-jdk15.jar
测试类:

(1)自定义JSON类对象

import net.sf.json.JSONObject;
public class TestJSON {
         public static void main(String[] args) {
                   JSONObject obj=new JSONObject();
                   obj.put("name", "zb");
                   obj.put("age", 20);
                   obj.put("birth", "1998-11-1");
                   System.out.println(obj);
         }
}

执行:{“birth”:”1998-11-1”,”age”:20,”name”:”zb”}

(2)由MAP生成JSON类对象

public class TestJSON {
         public static void main(String[] args) {
                   Map obj=new HashMap();
                   obj.put("name", "zb");
                   obj.put("age", 20);
                   obj.put("birth", "1998-11-1");
                   JSONObject objJSON=JSONObject.fromObject(obj);
                   System.out.println(objJSON);
         }
}

执行结果:{“birth”:”1998-11-1”,”name”:”zb”,”age”:20}

(3)由JAVA集合生成JSON数组对象

public class TestJSON {
         public static void main(String[] args) {
                   List<Map> list=new ArrayList<Map>();
                   Map obj1=new HashMap();
                   obj1.put("name", "zb");
                   obj1.put("age", 20);
                   obj1.put("birth", "1998-11-1");
                   list.add(obj1);
                   Map obj2=new HashMap();
                   obj2.put("name", "zb2");
                   obj2.put("age", 22);
                   obj2.put("birth", "1996-1-1");
                   list.add(obj2);
                   JSONArray array=JSONArray.fromObject(list);
                   System.out.println(array);
         }
}

执行结果:[{“birth”:”1998-11-1”,”age”:20,”name”:”zb”},{“birth”:”1996-1-1”,”age”:22,”name”:”zb2”}]

(4)由JavaBean生成JSON类对象

User类的定义:

package cn.sdut.po;
public class User {
         private int id;
         private String name;
         private String password;
         private String sex;
         private String birthday;
         private String hobby;
         private String telephone;
         private String address;
         private int type;     
         public User() {
                   super();
         }
         public User(int id, String name, String password, String sex,
                            String birthday, String hobby, String telephone, String address,
                            int type) {
                   super();
                   this.id = id;
                   this.name = name;
                   this.password = password;
                   this.sex = sex;
                   this.birthday = birthday;
                   this.hobby = hobby;
                   this.telephone = telephone;
                   this.address = address;
                   this.type = type;
         }
         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 String getPassword() {
                   return password;
         }
         public void setPassword(String password) {
                   this.password = password;
         }
         public String getSex() {
                   return sex;
         }
         public void setSex(String sex) {
                   this.sex = sex;
         }
         public String getBirthday() {
                   return birthday;
         }
         public void setBirthday(String birthday) {
                   this.birthday = birthday;
         }
         public String getHobby() {
                   return hobby;
         }
         public void setHobby(String hobby) {
                   this.hobby = hobby;
         }
         public String getTelephone() {
                   return telephone;
         }
         public void setTelephone(String telephone) {
                   this.telephone = telephone;
         }
         public String getAddress() {
                   return address;
         }
         public void setAddress(String address) {
                   this.address = address;
         }
         public int getType() {
                   return type;
         }
         public void setType(int type) {
                   this.type = type;
         }
         @Override
         public String toString() {
                   return "User [id=" + id + ", name=" + name + ", password=" + password
                                     + ", sex=" + sex + ", birthday=" + birthday + ", hobby="
                                     + hobby + ", telephone=" + telephone + ", address=" + address
                                     + ", type=" + type + "]";
         }
}

测试类:

package cn.sdut.po;
import net.sf.json.JSONObject;
public class TestJSON {
         public static void main(String[] args) {
                   User user=new User(1,"李华","1111","女","1999-1-1","体育","122342","淄博",1);
                   JSONObject userJson=JSONObject.fromObject(user);
                   System.out.println(userJson.toString());
         }
}

执行:{“id”:1,”birthday”:”1999-1-1”,”sex”:”女”,”address”:”淄博”,”name”:”李华”,”hobby”:”体育”,”type”:1,”telephone”:”122342”,”password”:”1111”}


2 AJAX异步请求


3 利用JSON+AJAX进行用户名的判断

过程分析:

(1)数据库层面的支持——根据用户名查询用户对象
(2)JSP页面的支持——“姓名”文本框内容改变时,需要响应onchange事件(或者onblur事件),另外,在姓名输入框后加个提示信息的控件,用于显示用户名是否可用。
(3)Servlet的处理——获得用户名,根据用户名查询用户,若查到,就返回页面“true”,否则返回“false”
(4)JSP页面根据返回值“true”还是“false”,进行不同的处理。 详细代码:

(1)数据库层面的支持——根据用户名查询用户对象(UserDao.java)

DBUtilsBaseDao.java

package cn.sdut.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
public class DBUtilsBaseDao {
         //得到数据库连接
         public  Connection getConn()
         {
                   Connection conn=null;
                   DbUtils.loadDriver("com.mysql.jdbc.Driver");
                   try {
                            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf-8","root","usbw");
                  } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                   }
                   return conn;
         }

         //增、删、改数据库的方法
         public int update(String sql,Object... param)
         {
                   int result=0;
                   Connection conn=getConn(); //得到连接
                   QueryRunner runner=new QueryRunner();  //得到运行对象
                   try {
                            result=runner.update(conn, sql, param); //进行数据库操作
                   } catch (SQLException e) {
                            e.printStackTrace();
                   }
                   finally
                   {
                            DbUtils.closeQuietly(conn);  //关闭数据库连接
                   }
                   return result;
         }

         //数据库查询
         public List query(String sql,Class clazz,Object... param)
         {
                   List list=null;
                   Connection conn=getConn(); //得到连接
                   QueryRunner runner=new QueryRunner();  //得到运行对象
                   try {
                            list=runner.query(conn,sql,new BeanListHandler(clazz),param); //进行数据库操作
                   } catch (SQLException e) {
                            e.printStackTrace();
                   }
                   finally
                   {
                            DbUtils.closeQuietly(conn);  //关闭数据库连接
                   }
                   return list;
         }

          //批量操作数据库的方法
                   public boolean bactchUpdate(String sql,Object[][] param)
                   {
                            int[] result=new int[param.length];
                            int r=1;                       
                            Connection conn=getConn(); //得到连接                         
                            QueryRunner runner=new QueryRunner();  //得到运行对象
                            try {
                                     result=runner.batch(conn,sql,param);// 批量进行数据库操作
                            } catch (SQLException e) {
                                     e.printStackTrace();
                            }
                            finally
                            {
                                     DbUtils.closeQuietly(conn);  //关闭数据库连接
                            }
                            //对返回数据进行加工,将整型数组转化为布尔类型
                            for(int i=0;i<result.length;i++)
                            {
                                     r*=result[i];
                            }
                            return r>0?true:false;
                   }
}

UserDao.java

package cn.sdut.dao;
import java.util.List;
import cn.sdut.po.User;
public class UserDao extends DBUtilsBaseDao {
         // ………….        
         //用户注册或增加用户时根据用户名查询用户(是否存在)
         public User findUserByName(String name)
         {
                   User user=null;
                   String sql="select * from users where name=?";
                   Object[] param=new Object[]{name};
                   List<User> users=query(sql, User.class, param);
                   if(users!=null&&users.size()>0)
                   {
                            user=users.get(0);
                   }                
                   return user;
         }
}

(2)JSP页面的支持——“姓名”文本框内容改变时,需要响应onchange事件(或者onblur事件),另外,在姓名输入框后加个提示信息的控件,用于显示用户名是否可用。(m_addUser.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 ’addUser.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 src="js/calendar.js"></script>
  <style type="text/css">
  body {
         text-align: center;
}
  </style>
  <script>
    function checkUser()
    {
       var name=document.getElementById("name").value;
       var httpRequest=new XMLHttpRequest();
       httpRequest.open("GET","<%=path%>/UserServlet?method=byname&name="+name,true);
       httpRequest.onreadystatechange=function()
       {
          if(httpRequest.status==200&&httpRequest.readyState==4)
          {
             var response=httpRequest.responseText;
             if(response=="true")
             {
               document.getElementById("info").innerHTML="用户名已存在";
               document.getElementById("name").value="";
             }
                            else
                            {
               document.getElementById("info").innerHTML="用户名可用";
}
          }
       }
       httpRequest.send();
    }
  </script>

  </head>

  <body>
  <br>
  <form name="form1" method="post" action="<%=path%>/UserServlet?method=add">
    <table width="496" border="1">
    <caption>用户添加</caption>
      <tr>
        <td width="92" height="38" align="center">用户名:</td>
        <td width="157">
<input type="text" name="name" id="name" onblur="checkUser()">
             <span id="info" style="color:red"></span>
        </td>
      </tr>
      <tr>
        <td height="41" align="center">密码:</td>
        <td><input type="text" name="password" id="password"></td>
      </tr>
      <tr>
        <td height="41" align="center">出生日期:</td>
        <td><input type="text" name="birthday" id="birthday" onclick="new Calendar().show(this)"></td>
      </tr>
      <tr>
        <td height="44" align="center">性别:</td>
        <td><input type="radio" name="sex" id="sex" value="男">男&nbsp;
           <input type="radio" name="sex" id="sex2" value="女"></td>
      </tr>
      <tr>
        <td align="center">爱好:</td>
        <td><p>
          <label>
            <input type="checkbox" name="hobby" value="运动" id="hobby_0">运动</label>
          <label>
            <input type="checkbox" name="hobby" value="音乐" id="hobby_1">音乐</label>
          <label>
            <input type="checkbox" name="hobby" value="阅读" id="hobby_2">阅读</label>
          <br>
        </p></td>
      </tr>
      <tr>
        <td align="center">地址:</td>
        <td><textarea name="address" id="address" cols="45" rows="5"></textarea></td>
      </tr>
      <tr>
        <td height="42" align="center">联系电话:</td>
        <td><input type="text" name="telephone" id="telephone"></td>
      </tr>
      <tr>
        <td height="64" colspan="2" align="center">
        <input type="submit" name="submit" id="submit" value="提交">
          &nbsp; &nbsp; &nbsp; 
        <input type="reset" name="button" id="button" value="取消"></td>
      </tr>
    </table>
  </form>
  </body>
</html>

(3)Servlet的处理——获得用户名,根据用户名查询用户,若查到,就返回页面“true”,否则返回“false”。(UserServlet.java)

package cn.sdut.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.sdut.dao.UserDao;
import cn.sdut.po.User;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
         private static final long serialVersionUID = 1L;
         UserDao userDao = new UserDao();

         public UserServlet() {
                   super();
                   // TODO Auto-generated constructor stub
         }

         protected void doGet(HttpServletRequest request,
                            HttpServletResponse response) throws ServletException, IOException {
                   request.setCharacterEncoding("utf-8");
                   response.setCharacterEncoding("utf-8");
                   String method = request.getParameter("method");
                   switch (method) {
                   //………
                   case "byname":
                            queryUserByName(request,response);
                            break;
                   }
         }

         private void queryUserByName(HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
                   String result="false";
                   String name = request.getParameter("name");  
                   User user = userDao.findUserByName(name);
                   if(user!=null)
                   {
                            result="true";
                   }
                   response.getWriter().write(result);
         }


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

}

(4)JSP页面根据返回值“true”还是“false”,进行不同的处理。(m_addUser.jsp)

var response=httpRequest.responseText;
             if(response=="true")
             {
               document.getElementById("info").innerHTML="用户名已存在";
               document.getElementById("name").value="";
             }
else
                            {
               document.getElementById("info").innerHTML="用户名可用";
}

(5)程序执行:

http://localhost:8080/adduser/m_addUser.jsp


4 利用JSON+AJAX进行省、市、区信息联动

过程分析:

(0)创建表syscode,向里面加入省、市、区的数据,建立与该表对应的实体类

/*
Navicat MySQL Data Transfer
Source Server         : 127.0.0.1_3306
Source Server Version : 50621
Source Host           : 127.0.0.1:3306
Source Database       : procitydis
Target Server Type    : MYSQL
Target Server Version : 50621
File Encoding         : 65001
Date: 2016-08-05 11:37:55
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for syscode
-- ----------------------------
DROP TABLE IF EXISTS `syscode`;
CREATE TABLE `syscode` (
  `pid` int(11) NOT NULL AUTO_INCREMENT,
  `pname` varchar(20) NOT NULL,
  `pcode` varchar(20) NOT NULL,
  `pvalue` varchar(20) NOT NULL,
  `fcode` varchar(20) NOT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of syscode
-- ----------------------------
INSERT INTO `syscode` VALUES (’1’, ’省市’, ’01’, ’北京’, ’0’);
INSERT INTO `syscode` VALUES (’2’, ’省市’, ’02’, ’上海’, ’0’);
INSERT INTO `syscode` VALUES (’3’, ’省市’, ’03’, ’广州’, ’0’);
INSERT INTO `syscode` VALUES (’4’, ’省市’, ’04’, ’山东’, ’0’);
INSERT INTO `syscode` VALUES (’5’, ’省市’, ’0101’, ’东城区’, ’01’);
INSERT INTO `syscode` VALUES (’6’, ’省市’, ’010101’, ’东华门街道’, ’0101’);
INSERT INTO `syscode` VALUES (’7’, ’省市’, ’010102’, ’景山街道’, ’0101 ’);
INSERT INTO `syscode` VALUES (’8’, ’省市’, ’0102’, ’西城区’, ’01’);
INSERT INTO `syscode` VALUES (’9’, ’省市’, ’010201’, ’西长安街街道’, ’0102’);
INSERT INTO `syscode` VALUES (’10’, ’省市’, ’010202’, ’广安门内街道’, ’0102 ’);
INSERT INTO `syscode` VALUES (’11’, ’省市’, ’0103’, ’朝阳区’, ’01’);
INSERT INTO `syscode` VALUES (’12’, ’省市’, ’010301’, ’南磨房地区’, ’0103’);
INSERT INTO `syscode` VALUES (’13’, ’省市’, ’010302’, ’高碑店地区’, ’0103 ’);
INSERT INTO `syscode` VALUES (’14’, ’省市’, ’0201’, ’黄浦’, ’02’);
INSERT INTO `syscode` VALUES (’15’, ’省市’, ’020101’, ’黄浦1’, ’0201’);
INSERT INTO `syscode` VALUES (’16’, ’省市’, ’020102’, ’黄浦2’, ’0201’);
INSERT INTO `syscode` VALUES (’17’, ’省市’, ’0202’, ’徐汇’, ’02’);
INSERT INTO `syscode` VALUES (’18’, ’省市’, ’020201’, ’徐汇1’, ’0202’);
INSERT INTO `syscode` VALUES (’19’, ’省市’, ’020201’, ’徐汇2’, ’0202’);
INSERT INTO `syscode` VALUES (’20’, ’省市’, ’0203’, ’长宁’, ’02’);
INSERT INTO `syscode` VALUES (’21’, ’省市’, ’020301’, ’长宁1’, ’0203’);
INSERT INTO `syscode` VALUES (’22’, ’省市’, ’020302’, ’长宁2’, ’0203’);
INSERT INTO `syscode` VALUES (’23’, ’省市’, ’0301’, ’越秀区’, ’03’);
INSERT INTO `syscode` VALUES (’24’, ’省市’, ’030101’, ’越秀1’, ’0301’);
INSERT INTO `syscode` VALUES (’25’, ’省市’, ’030102’, ’越秀2’, ’0301’);
INSERT INTO `syscode` VALUES (’26’, ’省市’, ’0302’, ’天河区’, ’03’);
INSERT INTO `syscode` VALUES (’27’, ’省市’, ’030201’, ’天河1’, ’0302’);
INSERT INTO `syscode` VALUES (’28’, ’省市’, ’030201’, ’天河2’, ’0302’);
INSERT INTO `syscode` VALUES (’29’, ’省市’, ’0303’, ’白云区’, ’03’);
INSERT INTO `syscode` VALUES (’30’, ’省市’, ’030301’, ’白云1’, ’0303’);
INSERT INTO `syscode` VALUES (’31’, ’省市’, ’030201’, ’白云2’, ’0303’);
INSERT INTO `syscode` VALUES (’32’, ’省市’, ’0401’, ’济南’, ’04’);
INSERT INTO `syscode` VALUES (’33’, ’省市’, ’040101’, ’历下’, ’0401’);
INSERT INTO `syscode` VALUES (’34’, ’省市’, ’030202’, ’槐荫’, ’0302’);
INSERT INTO `syscode` VALUES (’35’, ’省市’, ’0402’, ’青岛’, ’04’);
INSERT INTO `syscode` VALUES (’36’, ’省市’, ’040201’, ’市南’, ’0402’);
INSERT INTO `syscode` VALUES (’37’, ’省市’, ’040201’, ’黄岛’, ’0402’);
INSERT INTO `syscode` VALUES (’38’, ’省市’, ’0403’, ’烟台’, ’04’);
INSERT INTO `syscode` VALUES (’39’, ’省市’, ’040301’, ’荣成 ’, ’0403’);
INSERT INTO `syscode` VALUES (’40’, ’省市’, ’040302’, ’文登’, ’0403’);
INSERT INTO `syscode` VALUES (’41’, ’省市’, ’0405’, ’淄博’, ’04’);
INSERT INTO `syscode` VALUES (’42’, ’省市’, ’040501’, ’张店’, ’0405’);
INSERT INTO `syscode` VALUES (’43’, ’省市’, ’040502’, ’淄川’, ’0405’);
INSERT INTO `syscode` VALUES (’44’, ’省市’, ’040503’, ’周村’, ’0405’);
INSERT INTO `syscode` VALUES (’45’, ’省市’, ’040504’, ’临淄’, ’0405’);
INSERT INTO `syscode` VALUES (’46’, ’省市’, ’040505’, ’博山’, ’0405’);

Syscode.java

package cn.sdut.po;
public class Syscode {
         private int id;
         private String pname;
         private String pcode;
         private String pvalue;
         private String fcode;
         public int getId() {
                   return id;
         }
         public void setId(int id) {
                   this.id = id;
         }
         public String getPname() {
                   return pname;
         }
         public void setPname(String pname) {
                   this.pname = pname;
         }
         public String getPcode() {
                   return pcode;
         }
         public void setPcode(String pcode) {
                   this.pcode = pcode;
         }
         public String getPvalue() {
                   return pvalue;
         }
         public void setPvalue(String pvalue) {
                   this.pvalue = pvalue;
         }
         public String getFcode() {
                   return fcode;
         }
         public void setFcode(String fcode) {
                   this.fcode = fcode;
         }       
}

(1)数据库层面,提供查询省、市、区的方法

package cn.sdut.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
public class DBUtilsBaseDao {
         //得到数据库连接
         public  Connection getConn()
         {
                   Connection conn=null;
                   DbUtils.loadDriver("com.mysql.jdbc.Driver");
                   try {
                            conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf-8","root","usbw");
                   } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                   }
                   return conn;
         }

         //增、删、改数据库的方法
         public int update(String sql,Object... param)
         {
                   int result=0;
                   Connection conn=getConn(); //得到连接
                   QueryRunner runner=new QueryRunner();  //得到运行对象
                   try {
                            result=runner.update(conn, sql, param); //进行数据库操作
                   } catch (SQLException e) {
                            e.printStackTrace();
                   }
                   finally
                   {
                            DbUtils.closeQuietly(conn);  //关闭数据库连接
                   }
                   return result;
         }

         //数据库查询
         public List query(String sql,Class clazz,Object... param)
         {
                   List list=null;
                   Connection conn=getConn(); //得到连接
                   QueryRunner runner=new QueryRunner();  //得到运行对象
                   try {
                            list=runner.query(conn,sql,new BeanListHandler(clazz),param); //进行数据库操作
                   } catch (SQLException e) {
                            e.printStackTrace();
                   }
                   finally
                   {
                            DbUtils.closeQuietly(conn);  //关闭数据库连接
                   }
                   return list;
         }

          //批量操作数据库的方法
                   public boolean bactchUpdate(String sql,Object[][] param)
                   {
                            int[] result=new int[param.length];
                            int r=1;                       
                            Connection conn=getConn(); //得到连接                         
                            QueryRunner runner=new QueryRunner();  //得到运行对象
                            try {
                                     result=runner.batch(conn,sql,param);// 批量进行数据库操作
                            } catch (SQLException e) {
                                     e.printStackTrace();
                            }
                            finally
                            {
                                     DbUtils.closeQuietly(conn);  //关闭数据库连接
                            }
                            //对返回数据进行加工,将整型数组转化为布尔类型
                            for(int i=0;i<result.length;i++)
                            {
                                     r*=result[i];
                            }
                            return r>0?true:false;
                   }
}

package cn.sdut.dao;

import java.util.List;
import cn.sdut.po.Syscode;
public class SyscodeDao extends DBUtilsBaseDao {
         public List<Syscode> findPCD(String pname, String fcode) {
                   List<Syscode> pcd = null;
                   String sql = "select * from syscode where pname=? and fcode=?";
                    pcd=query(sql, Syscode.class, new String[] { pname, fcode });
                    System.out.println(pcd);
                    return pcd;
         }
}

(2)页面层提供省、市、区3个下拉列表框,实现信息联动。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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 showCity()
           { //显示市
            var value=document.getElementById("province").value;
              var httpRequest=new XMLHttpRequest();
              httpRequest.open("GET","<%=path%>/SyscodeServlet?method=city&fcode="+value,true);
                    httpRequest.onreadystatechange=function(){
                       if(httpRequest.status==200 && httpRequest.readyState==4)
                       {
                         var cities=httpRequest.responseText;
                         var jsonCities=eval("("+cities+")");
                         var obj=document.getElementById("city");
                         obj.options.length=0;
                         for(var i=0;i<jsonCities.length;i++)
                         {
                            obj.add(new Option(jsonCities[i].pvalue,jsonCities[i].pcode));
                         }
                         showDist();
                       }
                    };
                    httpRequest.send();        
           }
           function showDist()
           {  //显示区
              var value=document.getElementById("city").value;
              var httpRequest=new XMLHttpRequest();
              httpRequest.open("GET","<%=path%>/SyscodeServlet?method=city&fcode="+value,true);
                    httpRequest.onreadystatechange=function(){
                       if(httpRequest.status==200 && httpRequest.readyState==4)
                       {
                         var cities=httpRequest.responseText;
                         var jsonCities=eval("("+cities+")");
                         var obj=document.getElementById("dist");
                         obj.options.length=0;
                         for(var i=0;i<jsonCities.length;i++)
                         {
                            obj.add(new Option(jsonCities[i].pvalue,jsonCities[i].pcode));
                         }
                       }
                    };
                    httpRequest.send();        
           }
         </script>
  </head>

  <body onload="showCity()">
     <select id="province" name="province" onchange="showCity()">
             <c:forEach items="${provinceList }" var="province">
                <option value="${province.pcode }">${province.pvalue }</option>
             </c:forEach>
     </select>
     <select id="city" name="city" onchange="showDist()">
     </select>
     <select id="dist" name="dist">
     </select>
  </body>
</html>

(3)Servlet层面——完成2个任务:

l 页面加载时显示所有省的信息; l 异步请求显示市和区的信息

package cn.sdut.servlet;
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 net.sf.json.JSONObject;
import cn.sdut.dao.SyscodeDao;
import cn.sdut.po.Syscode;
public class SyscodeServlet extends HttpServlet {
         public void doGet(HttpServletRequest request, HttpServletResponse response)
                            throws ServletException, IOException {
                   request.setCharacterEncoding("utf-8");
                   response.setCharacterEncoding("utf-8");
                   String method=request.getParameter("method");
                   switch(method)
                   {
                   case "province":
                            queryProvince(request,response);
                            break;
                   case "city":
                            queryCity(request,response);
                            break;
                   case "dist":
                            queryCity(request,response);
                            break;
                   }
         }

         private void queryProvince(HttpServletRequest request,
                            HttpServletResponse response) throws ServletException, IOException {

                   SyscodeDao dao=new SyscodeDao();
                   List<Syscode> provinceList = dao.findPCD("省市", "0");
                   //System.out.println(provinceList);
                   request.setAttribute("provinceList", provinceList);            
                   request.getRequestDispatcher("/index.jsp").forward(request, response);
         }

         private void queryCity(HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
                   System.out.println(11);
                   String fcode=request.getParameter("fcode");
                   SyscodeDao dao=new SyscodeDao();
                   List<Syscode> provinceList = dao.findPCD("省市", fcode);
                   JSONArray cities=JSONArray.fromObject(provinceList);
                   System.out.println(provinceList);
                   response.getWriter().write(cities.toString());               
         }

         public void doPost(HttpServletRequest request, HttpServletResponse response)
                            throws ServletException, IOException {
                   doGet(request,response);
         }
}

(4)执行:

http://localhost:8080/PCD/SyscodeServlet?method=province

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值