My Java Development-Ajax case: Using ajax to implement automatic completion (below)

Source: Internet
Author: User

Automatic completion using Ajax

Basedao. Java

Package COM. LJ. dao; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. SQL. sqlexception; public class basedao {/*** generates a servletid */Private Static final long serialversionuid =-3005086949118705373l; // define the connection constant Private Static final string driver_name = "com. microsoft. JDBC. sqlserver. sqlserverdriver "; Private Static final stri Ng driver_url = "JDBC: sqlserver: // localhost: 1433; databasename = sellcomputer"; Private Static final string db_user_name = "sa"; Private Static final string db_user_pwd = "sa "; // obtain the public static connection getconn () throws classnotfoundexception, sqlexception {class. forname (driver_name); connection conn = drivermanager. getconnection (driver_url, db_user_name, db_user_pwd); Return conn;} // public static Conne Ction getconn () throws namingexception, sqlexception {// initialize the application context // initialcontext Ic = new initialcontext (); // Java: COMP/ENV is a fixed prefix, JDBC/empdatabase1 is the name of the configured data source // datasource conn = (datasource) IC. lookup ("Java: COMP/ENV/jdbc/News"); // return Conn. getconnection (); //} // release the database resource public static void closeall (connection Conn, preparedstatement ps, resultset RS) {If (RS! = NULL) Try {Rs. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}if (PS! = NULL) Try {ps. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}if (Conn! = NULL) Try {conn. Close () ;}catch (sqlexception e) {e. printstacktrace ();}}}

 

Computerdao. Java

Package COM. LJ. dao; import Java. SQL. connection; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. util. arraylist; import Java. util. list; import COM. LJ. entity. PC; public class computerdao extends basedao {Private Static connection conn = NULL; // Save the database connection Private Static preparedstatement PS = NULL; // execute the SQL statement Private Static resultset rs = NULL; // used to save the query result set // Add a method to query data from the database and return the public list as a set <Pc> getallpoll (string keyword) {list <Pc> List = new arraylist <Pc> (); try {conn = basedao. getconn (); string SQL = "select * from PC where pcname like '" + keyword + "%'"; PS = Conn. preparestatement (SQL); RS = ps.exe cutequery (); While (RS. next () {PC Pc = new PC (); PC. setid (RS. getint ("ID"); PC. setpcname (RS. getstring ("pcname"); list. add (PC) ;}} catch (classnotfoundexception e) {e. printstacktrace ();} catch (sqlexception e) {e. printstacktrace ();} finally {basedao. closeall (Conn, PS, RS);} return list ;}}

 

PC. Java

package com.LJ.entity;public class PC {private int id;private String pcname;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getPcname() {return pcname;}public void setPcname(String pcname) {this.pcname = pcname;}public PC(int id, String pcname) {super();this.id = id;this.pcname = pcname;}public PC() {super();}}

 

Computerservlet. Java

Package COM. LJ. 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 COM. LJ. dao. computerdao; import COM. LJ. entity. PC; public class computerservlet extends httpservlet {Private Static final long serialversionuid =-response; @ overrideprotected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// set the character set req for receiving information. setcharacterencoding ("UTF-8"); // receives information submitted by the browser end // string action = req. getparameter ("action"); string name = req. getparameter ("names"); // sets the format and character resp of the output information. setcontenttype ("text/XML; charset = UTF-8"); resp. setheader ("cache-control", "No-Cache"); // create the output stream printwriter out = resp. getwriter (); // outputs different data information out based on the result. print ("<response>"); computerdao = new computerdao (); List <Pc> List = computerdao. getallpoll (name); For (INT I = 0; I <list. size (); I ++) {PC Pc = List. get (I); out. println ("<res>" + PC. getpcname () + "</RES>");} Out. print ("</response>"); out. close () ;}@ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {This. doget (req, resp );}}

 

Computerdaotest. Java

package com.LJ.test;import java.util.List;import com.LJ.dao.ComputerDao;import com.LJ.entity.PC;public class ComputerDaoTest {public static void main(String[] args) {ComputerDao computerDao = new ComputerDao();List<PC> list = computerDao.getAllPoll("H");for(int i = 0;i<list.size();i++){PC pc = list.get(i);System.out.println(pc.getPcname());}}}

 

Ctrf. js

VaR xmlhttpreq; var completediv; var inputfield; var completetable; var completebody; // create the XMLHTTPRequest object function createxmlhttprequest () {// create the XMLHTTPRequest object if (window. XMLHttpRequest) {// IE7, IE8, Firefox, javasillar, and operabrowser xmlhttpreq = new XMLHttpRequest (); // when the header is not set in text/XML format, you need to reset it to text/xmlif (xmlhttpreq. overridemimetype) {xmlhttpreq. overridemimetype ("text/XML") ;}} else if (window. activexobject) {// IE6, Ie5, ie5.5, because all browsers are based on activexobject, it is better to put them behind the scenes to implement var activexname = ["msxml2.xmlhttp. 6.0 "," msxml2.xmlhttp. 5.0 "," msxml2.xmlhttp. 4.0 "," msxml2.xmlhttp. 3.0 "," msxml2.xmlhttp "," miscrosoft. XMLHTTP "]; for (VAR I = 0; I <activexname. length; I ++) {try {xmlhttpreq = new activexobject (activexname [I]); break; // 1. You do not need to judge whether the object is created successfully} catch (E) {// exception does not need to be processed }}// send the function findnames () {inputfield = document. get Elementbyid ("names"); completetable = document. getelementbyid ("complete_table"); completediv = document. getelementbyid ("popup"); completebody = document. getelementbyid ("complete_body"); If (inputfield. value. length> 0) {createxmlhttprequest (); var url = "computerservlet? Names = "+ escape (inputfield. value); // alert (URL); xmlhttpreq. open ("get", URL, true); xmlhttpreq. onreadystatechange = processmatchresponse; xmlhttpreq. send (null) ;}else {clearnames () ;}// function processmatchresponse () {// according to the status // alert ("the current status is: "+ xmlhttpreq. readystate); // determines the object state if (xmlhttpreq. readystate = 4) {// determine whether the response is successful if (xmlhttpreq. status = 200) {// 1. setnames (xmlhttpreq. responsexml. getelementsbytagname ("res"); // 2. Receive the returned data in text format // var respinfomation = xmlhttpreq. responsetext; // alert (respinfomation);} else {alert ("response exception") ;}}// function setnames (names) {clearnames (); var size = names. length; setoffsets (); var row, cell, txtnode; For (VAR I = 0; I <size; I ++) {var nextnode = Names [I]. firstchild. data; ROW = document. createelement ("TR"); cell = document. createelement ("TD"); cell. onmouseout = function () {This. classname = 'mouseover';}; cell. onmouseover = function () {This. classname = 'mouseout';}; cell. setattribute ("bgcolor", "# fffafa"); cell. setattribute ("border", 0); cell. onclick = function () {completefield (this) ;}; txtnode = document. createtextnode (nextnode); cell. appendchild (txtnode); row. appendchild (cell); completebody. appendchild (ROW) ;}/// set the display position function setoffsets () {completetable. style. width = inputfield. offsetwidth; + "PX"; var left = calculateoffset (inputfield, "offsetleft"); var Top = calculateoffset (inputfield, "offsettop") + inputfield. offsetheight; completediv. style. border = "Black 1px solid"; completediv. style. left = left + "PX"; completediv. style. top = Top + "PX" ;}// calculate the display position function calculateoffset (field, ATTR) {var offset = 0; while (field) {Offset + = field [ATTR]; field = field. offsetparent;} return offset;} // enter the input box function completefield (cell) {inputfield. value = cell. firstchild. nodevalue; clernames ();} // clear the automatically completed row function clearnames () {var ind = completebody. childnodes. length; For (vari = ind-1; I> = 0; I ++) {completebody. removechild (completebody. childnodes [I]);} completediv. style. border = "NONE ";}

Web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><servlet-name>computerServlet</servlet-name><servlet-class>com.LJ.servlet.ComputerServlet</servlet-class></servlet><servlet-mapping><servlet-name>computerServlet</servlet-name><url-pattern>/computerServlet</url-pattern></servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

 

Index. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <HTML> 

 

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.