Ajax achieves provincial-municipal three-level linkage V1.1

Source: Internet
Author: User

This is a servlet application ..

This version uses the JSON-lib toolkit. For how to use JSON-lib, see my blog

Http://blog.csdn.net/jadyer/archive/2011/02/01/6171659.aspx

The first is the Web. xml file.

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" <br/> xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" <br/> xsi: schemalocation = "http://java.sun.com/xml/ns/javaee <br/> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <br/> <servlet-Name> initprovinceservlet </servlet-Name> <br/> <Servlet -Class> COM. jadyer. servlet. initprovinceservlet </servlet-class> <br/> </Serv Let> <br/> <servlet-Name> getcityservlet </servlet-Name> <br/> <servlet-class> COM. jadyer. servlet. getcityservlet </servlet-class> <br/> </servlet> <br/> <servlet-Name> getareaservlet </servlet-Name> <br /> <servlet-class> COM. jadyer. servlet. getareaservlet </servlet-class> <br/> </servlet> </P> <p> <servlet-mapping> <br/> <servlet-Name> initprovinceservlet </Servlet -Name> <br/> <URL-Pattern >/Servlet/initprovinceservlet </url-pattern> <br/> </servlet-mapping> <br/> <servlet-Name> getcityservlet </servlet-Name> <br/> <URL-pattern>/servlet/getcityservlet </url-pattern> <br/> </servlet-mapping> <br/> <servlet-mapping> <br/> <servlet-Name> getareaservlet </servlet-Name> <br/> <URL-pattern>/servlet/getareaservlet </url-pattern> <br/> </servlet-mapping> </P> <p> <! -In version = "2.5, you can directly execute the servlet application in <welcome-file-List> <br/> <welcome-File> Servlet/initprovinceservlet </welcome-File> <br/> </welcome-file-List> <br/> </Web-app>

Then the index. jsp page is used to display the effect of provincial-municipal three-level linkage

<% @ Page Language = "Java" pageencoding = "UTF-8" %> <br/> <% @ taglib prefix = "C" uri = "http://java.sun.com/jsp/jstl/core" %> <br/> <style> <br/> # area {<br/> background-color: # ffffc0; <br/> font-size: 12px; <br/> color: green; <br/>}< br/> </style> <br/> <SCRIPT type = "text/JavaScript"> <br/> var XMLHTTP = new XMLHttpRequest (); // Internet Explorer-8.0.6001.18702 supported </P> <p> function getcitys (provinceid) {<br/> // if the province option is selected If "= select province =", the city list data is cleared, and the "= select city =" text = "<br/> If ('0' = provinceid) {<br/> paiitys (); <br/> return; <br/>}< br/> XMLHTTP. open ('get', '$ {pagecontext. request. contextpath}/servlet/getcityservlet? Provinceid = '+ provinceid, true); <br/> XMLHTTP. onreadystatechange = callbackcitys; // sets the callback function <br/> XMLHTTP. setRequestHeader ("If-modified-since", "0"); // you can disable browser caching. <br/> XMLHTTP. send (null); // send the request <br/>}</P> <p> function callbackcitys () {<br/> If (4 = XMLHTTP. readystate & 200 = XMLHTTP. status) {<br/> // The returned data is similar to [{"areas": [], "cityid": 4, "cityname": "Harbin ", "Description": "famous ice City", "parentid": 0 },{ "areas": [], "cityid": 5, "cityname": "Jiamusi", "Description": "legendary thief City", "parentid": 0 },{ "areas": [], "cityid": 6, "cityname": "Shuangyashan", "Description": "Manchu origin", "parentid ": 0}] <br/> var citys = eval (XMLHTTP. responsetext); <br/> inititys (); <br/> var city = document. getelementbyid ("city"); <br/> for (VAR I = 0; I <Citys. length; I ++) {<br/> city. options [I + 1] = New Option (citys [I]. cityname, citys [I]. cityid); // New Option (text, value) <br/>}< B R/>}</P> <p> // clear city list data <br/> function compute itys () {<br/> var city = document. getelementbyid ('city'); <br/> document. getelementbyid ("area "). innerhtml = ""; <br/> city. length = 0; <br/> city. options [0] = New Option ('= select city =', '0'); <br/>}</P> <p> function getarea (cityid) {<br/> If ('0' = cityid) {<br/> document. getelementbyid ("area "). innerhtml = ""; <br/> return; <br/>}< br/> XMLHTTP. open ('get', '$ {pagecont Ext. Request. contextpath}/servlet/getareaservlet? Cityid = '+ cityid, true); <br/> XMLHTTP. onreadystatechange = callbackarea; <br/> XMLHTTP. setRequestHeader ("If-modified-since", "0"); <br/> XMLHTTP. send (null); <br/>}</P> <p> function callbackarea () {<br/> If (4 = XMLHTTP. readystate & 200 = XMLHTTP. status) {<br/> // The returned data is similar to [{"areas": [{"areas": [], "cityid": 13, "cityname ": "Bayan County", "Description": "My Hometown", "parentid": 0 },{ "areas": [], "cityid": 14, "cityname ": "yanshou county", "Description": "yanshou Villa", "parentid": 0 },{ "areas": [], "cityid": 15, "cityname ": "Mulan county", "Description": "cihang ancient temple", "parentid": 0}], "cityid": 4, "cityname": "Harbin", "Description ": "famous ice City", "parentid": 0}] <br/> var city = eval ('+ XMLHTTP. responsetext + '); <br/> var MSG = "<p> <B>" + city. cityname + "City:" + city. description + "</B> <br/>"; <br/> If (0 = city. areas. length) {<br/> MSG + = "No districts and counties"; <br/>} else {<br/> MSG + = "under it" + city. areas. length + "districts and counties, followed by: <br/>"; <br/> var areas = city. areas; <br/> for (VAR I = 0; I <areas. length; I ++) {<br/> MSG + = ("name:" + areas [I]. cityname + "& nbsp; Description:" + areas [I]. description + "<br/>"); <br/>}< br/> MSG + = "</P>"; <br/> document. getelementbyid ("area "). innerhtml = MSG; <br/>}< br/> </SCRIPT> </P> <p> province: <br/> <select id = "Province" onchange = "getcitys (this. value) "> <br/> <option value =" 0 ">== select a province ==</option> <br/> <C: foreach items = "$ {requestscope. provinces} "Var =" Province "> <br/> <option value =" $ {province. cityid} ">$ {province. cityname }</option> <br/> </C: foreach> <br/> </SELECT> <br/> city: <br/> <select id = "city" onchange = "getarea (this. value) "> <br/> <option >== select city ==</option> <br/> </SELECT> <br/> <Div id =" area "> </div>

Then, citydao. Java is used to perform query operations from the database.

Package COM. jadyer. dao; </P> <p> Import Java. SQL. connection; <br/> Import Java. SQL. preparedstatement; <br/> Import Java. SQL. resultset; <br/> Import Java. SQL. sqlexception; <br/> Import Java. util. arraylist; <br/> Import Java. util. list; </P> <p> Import javax. naming. context; <br/> Import javax. naming. initialcontext; <br/> Import javax. naming. namingexception; <br/> Import javax. SQL. datasource; </P> <p> Import COM. jadyer. Model. city; </P> <p>/** <br/> * The code here should be reconstructed, but for convenience of demonstration, no reconstruction <br/> */<br/> public class citydao {<br/>/** <br/> * obtain all primary classes based on the parent id <br/> * @ see if 0 is passed, all the root nodes <br/> */<br/> public list <city> findbyparentid (INT parentid) {<br/> string SQL = "select cityid, cityname, description from city where parentid =? "; <Br/> List <city> citys = new arraylist <city> (); <br/> try {<br/> context = new initialcontext (); <br/> // For JDBC/oracleds connection pool configuration, see http://blog.csdn.net/jadyer/archive/2010/11/10/6001023.aspx <br/> datasource DS = (datasource) context. lookup ("Java:/COMP/ENV/jdbc/oracleds"); <br/> connection conn = Ds. getconnection (); <br/> preparedstatement pstmt = Conn. preparestatement (SQL); <br/> pstmt. setint (1, Parentid); <br/> resultset rs = pstmt.exe cutequery (); <br/> while (RS. next () {<br/> Citys. add (New City (RS. getint ("cityid"), RS. getstring ("cityname"), RS. getstring ("Description"); <br/>}< br/>} catch (namingexception e) {<br/> E. printstacktrace (); <br/>} catch (sqlexception e) {<br/> E. printstacktrace (); <br/>}< br/> return citys; <br/>}</P> <p>/** <br/> * obtain detailed information about the city based on the ID. <br/> */<br/> Public City fing Bycityid (INT cityid) {<br/> string SQL = "select cityname, description from city where cityid =? "; <Br/> city City = NULL; <br/> try {<br/> context = new initialcontext (); <br/> datasource DS = (datasource) context. lookup ("Java:/COMP/ENV/jdbc/oracleds"); <br/> connection conn = Ds. getconnection (); <br/> preparedstatement pstmt = Conn. preparestatement (SQL); <br/> pstmt. setint (1, cityid); <br/> resultset rs = pstmt.exe cutequery (); <br/> while (RS. next () {<br/> city = New City (cityid, Rs. getstring ("cityname"), RS. getstring ("Description"); <br/>}< br/>} catch (namingexception e) {<br/> E. printstacktrace (); <br/>} catch (sqlexception e) {<br/> E. printstacktrace (); <br/>}< br/> return city; <br/>}< br/>}

Entity class used to store city information

Package COM. jadyer. model; </P> <p> Import Java. util. list; </P> <p> public class city {<br/> private integer parentid; <br/> private integer cityid; <br/> private string cityname; <br/> private string description; <br/> private list <city> areas; // added .. Used to store detailed information of all districts and counties in the city </P> <p>/* getter and setter methods for five attributes </P> <p> Public City () {}</P> <p> Public City (integer cityid, string cityname, string description) {<br/> This. cityid = cityid; <br/> This. cityname = cityname; <br/> This. description = description; <br/>}< br/>}

Initprovinceservlet. java used to initialize information of all provinces

Package COM. jadyer. servlet; </P> <p> Import Java. io. ioexception; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletresponse; </P> <p> Import COM. jadyer. dao. citydao; </P> <p> @ suppresswarnings ("serial") <br/> public class initprovinceservlet extends httpservlet {<br/> Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {<br/> citydao = new citydao (); <br/> // obtain information of all provinces <br/> request. setattribute ("provinces", citydao. findbyparentid (0); <br/> request. getrequestdispatcher ("/index. JSP "). forward (request, response); <br/>}< br/>}

Getcityservlet. java used to obtain information about all cities in a specified Province

Package COM. jadyer. servlet; </P> <p> Import Java. io. ioexception; <br/> Import Java. util. list; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletresponse; </P> <p> Import net. SF. JSON. jsonarray; </P> <p> Import COM. jadyer. dao. citydao; <br/> Import COM. jadyer. model. city; </P> <p> @ suppresswarnings ("serial") <br/> public class getcityservlet extends httpservlet {<br/> Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {<br/> response. setcontenttype ("text/html; charset = UTF-8"); <br/> int provinceid = integer. parseint (request. getparameter ("provinceid"); <br/> citydao = new citydao (); <br/> // return information of all cities in the province. <br/> List <city> citys = citydao. findbyparentid (provinceid); <br/> jsonarray jsonobject = jsonarray. fromobject (citys); <br/> response. getwriter (). println (jsonobject. tostring (); <br/>}< br/>}

Getareaservlet. Java

Package COM. jadyer. servlet; </P> <p> Import Java. io. ioexception; <br/> Import Java. util. list; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletresponse; </P> <p> Import net. SF. JSON. jsonobject; </P> <p> Import COM. jadyer. dao. citydao; <br/> Import COM. jadyer. model. city; </P> <p> @ suppresswarnings ("serial") <br/> public class getareaservlet extends httpservlet {<br/> Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {<br/> response. setcontenttype ("text/html; charset = UTF-8"); <br/> int cityid = integer. parseint (request. getparameter ("cityid"); <br/> citydao = new citydao (); <br/> // obtain a set of detailed information about all districts and counties in the city. <br/> List <city> areas = citydao. findbyparentid (cityid); <br/> // obtain the details of the current city. <br/> city city22 = citydao. fingbycityid (cityid); <br/> city22.setareas (areas); <br/> jsonobject = jsonobject. fromobject (city22); <br/> response. getwriter (). println (jsonobject. tostring (); <br/>}< br/>}

Finally, the database script file

-- Oracle 11g <br/> -- create a table <br/> Create Table City (<br/> ID number (3) primary key, <br/> parentid number (3), -- 0 indicates the root node <br/> cityid number (3), <br/> cityname varchar (20 ), <br/> description varchar (20) <br/>) </P> <p> -- create sequence <br/> Create sequence city_sequence increment by 1 start with 1 nomaxvalue nocycle; </P> <p> -- add Level 1 menu <br/> insert into city values (city_sequence.nextval, 0, 1, 'heilongjiang ', 'heilongjiang province in Northeast China '); <br/> insert into city values (city_sequence.nextval, 0, 2, 'Jilin province ', 'Jilin province in Northeast China'); <br/> insert into city values (city_sequence.nextval, 0, 3, 'liaoning province ', 'liaoning province in Northeast China'); <br/> -- add Level 2 menu <br/> insert into city values (city_sequence.nextval, 1, 4, 'harbin ', 'famous icket'); <br/> insert into city values (city_sequence.nextval, 1, 5, 'jiamusi ', 'legendary thief City '); <br/> insert into city values (city_sequence.nextval, 1, 6, 'shuangyashan, 'manchu original'); <br/> insert into city values (city_sequence.nextval, 2, 7, 'changchun ', 'automobile capital of China'); <br/> insert into city values (city_sequence.nextval, 2, 8, 'liaoyuan', 'hometown of China Pi '); <br/> insert into city values (city_sequence.nextval, 2, 9, 'tonghua ', 'city of Chinese medicine'); <br/> insert into city values (city_sequence.nextval, 3, 10, 'shenyang ', 'excellent Chinese tourist City'); <br/> insert into city values (city_sequence.nextval, 3, 11, 'dalian', 'First Navy square in China '); <br/> insert into city values (city_sequence.nextval, 3, 12, 'tieling ', 'hometown of little pinking '); <br/> -- add a three-level menu <br/> -- only the three-level linkage data of Heilongjiang Province is provided. For data about other provinces, add <br/> insert into city values (city_sequence.nextval, 4, 13, 'bayannayay', 'My home') by yourself; <br/> insert into city values (city_sequence.nextval, 4, 14, 'yanshou County ', 'yanshou Villa'); <br/> insert into city values (city_sequence.nextval, 4, 15, 'mulan County ', 'cihang gusi '); <br/> insert into city values (city_sequence.nextval, 5, 16, 'suwon ay', 'White four grandcans'); <br/> insert into city values (city_sequence.nextval, 5, 17, 'tangyuan County ', 'silang juncheng'); <br/> insert into city values (city_sequence.nextval, 5, 18, 'huachuan County ', 'Land of fish and rice '); <br/> insert into city values (city_sequence.nextval, 6, 19, 'ji xianxian ', 'Da Bodhi si'); <br/> insert into city values (city_sequence.nextval, 6, 20, 'babyqingxian ', 'nest island'); <br/> insert into city values (city_sequence.nextval, 6, 21, 'youyouxian ', 'zhongsu youyi ');

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.