Java Project (1) -- use Ajax Asynchronous interaction technology to verify whether user code is duplicated.
The DRP project involves the registration of users. this article describes how to use Ajax Asynchronous interaction to verify whether a user name already exists during registration. in the past, Ajax technology was not used in many projects. The result was that all judgments were executed when the submit button was clicked. The result was nothing more than the website card/software was dead, they all say that they will not die, so Ajax is widely used. users give thumbs up and praise it. They have to say That Ajax has captured web users ~~
Before implementation, first understand the five States of AjaxreadyState.
As I am more and more inclined to use the original English version, I think it will be easier to understand from its source, so I use the English explanation below, and I will understand it later.
0: (Uninitialized) thesend () method has not yet been invoked.
(Not initialized) The send () method has not been called. Only the xmlHttpRequest object has been created. Otherwise, the browser will report an error if the object does not exist ~
1: (Loading) the send () method has been invoked, request in progress.
(Load) The send () method has been called and a request is being sent. In this step, open () is called to set three parameters: method, url, and True. Then send () is called to send a request to the server.
2: (Loaded) the send () method has completed, entire response received ed.
(Load completed) The send () method is executed successfully. At this time, the original data is received from the server. A response does not indicate that the request is successful, including request success and failure.
3: (Interactive) theresponse is being parsed.
(Interaction) The response content is being parsed. parse the raw data obtained in the previous state and convert the data into a format that can be accessed through the responseBody, responseText, and responseXML attributes for the client to call.
4: (Completed) theresponse has been parsed, is ready for harvesting.
(Complete) after parsing is completed, the client can call it to obtain data through the response attribute of the XMLHttpRequest object.
HTML: when you enter the user name and press the table key to switch the input box, the onBlur event is triggered when the user name input box loses focus, and the validate () method is called immediately.
<Tr> <td width = "22%" height = "29"> <div align = "right"> <font color = "# FF0000"> * </font> User code: </div> </td> <td width = "78%"> <input name = "userId" type = "text" class = "text1" id = "userId" size = "10" maxlength = "10" onkeypress = "userIdOnKeyPress () "value =" <% = userId %> "onblur =" validate (this) "> <span id =" spanUserId "> </span> </td> </tr>
The User_add.jsp Page code uploads the userId to the user_validate.jsp page to check whether the page exists and receives the message using callback:
Var xmlHttp = null; function createXMLHttpRequest () {// indicates that the current browser is not ie, such as ns, firefoxif (window. XMLHttpRequest) {xmlHttp = new XMLHttpRequest ();} else if (window. activeXObject) {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ") ;}} function validate (field) {if (trim (field. value ). length! = 0) {// create the Ajax core object XMLHttpRequestcreateXMLHttpRequest (); var url = "user_validate.jsp? UserId = "+ trim (field. value) + "& time =" + new Date (). getTime (); // set the request method to get, request URL, and submit xmlHttp asynchronously. open ("GET", url, true); // assign the method address to the onreadystatechange attribute xmlHttp. onreadystatechange = callback; xmlHttp. send (null);} else {document. getElementById ("spanUserId "). innerHTML = "" ;}} function callback () {// 4 indicates a response if (xmlHttp. readyState = 4) {// 200 indicates that the request is successful if (xmlHttp. state = 200) {document. getElementById ("spanUserId "). innerHTML = "<font color = 'red'>" + xmlHttp. responseText + "</font>"} else {document. getElementById ("spanUserId "). innerHTML = "" ;}} else {alert ("request failed, error code =" + xmlHttp. status );}}
On the user_validate.jsp page, check whether the user ID already exists:
<% String userId = request. getParameter ("userId"); if (UserManager. getInstance (). findUserById (userId )! = Null) {out. println ("User code already exists") ;}%>
In UserManager. Java, the specific method for querying whether the database exists has been omitted:
public User findUserById(String userId){String sql="select user_id,user_name,password,contact_tel,create_date from t_user where user_id=?";Connection conn=null;PreparedStatement pstmt=null;ResultSet rs=null;User user=null;try{conn=DbUtil.getConnection();pstmt=conn.prepareStatement(sql);pstmt.setString(1,userId);rs=pstmt.executeQuery();if(rs.next()){ user=new User();user.setUserId(userId);user.setUserName(rs.getString("user_name"));user.setPassword(rs.getString("contact_tel"));user.setEmail(rs.getString("email"));user.setCreateDate(rs.getTimestamp("create_date"));}}catch(SQLException e){e.printStackTrace();}finally{DbUtil.close(rs);DbUtil.close(pstmt);DbUtil.close(conn);}return user;}
Conclusion: The Asynchronous interaction with the database using Ajax solves the problem of waiting for the user in the synchronous state. It is verified over there. this greatly improves the user experience, which is dynamic, fast response, and highly interactive.
Repeated JAVA User Name verification,
The text box can trigger this event when the onChange value changes and call Ajax to initiate an asynchronous request to the background to check whether the user name exists and then return the front-end. The difficulty lies in sending Ajax requests. You can use jQuery, of course. the amount of self-written Ajax code is not large
Var xmlhttp; // create the XMLHttpRequest object function createHttpRequest () {try {xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {xmlhttp = new ActiveXObject ("Microsoft. XMLHTTP ");} catch (e) {try {xmlhttp = new XMLHttpRequest (); if (xmlhttp. overrideMimeType) {xmlhttp. overrideMimeType ("text/xml") ;}} catch (e) {}}}// set the request information through the XMLHttpRequest object and send the request function doAjax (url) {createHttpRequest (); xmlhttp. onr Eadystatechange = processFunc; // sets the callback function xmlhttp. open ("get", "request address and parameter" + Math. random (), true); // open the corresponding link of the server xmlhttp. send (null); // send request} // create a callback function. Update the page function processFunc () {if (xmlhttp. readyState = 4) if (xmlhttp. status = 200) {var bool = xmlhttp. responseText; if (bool = "true") {alert ("the user name already exists! ");} Else {alert (" the user name can be used! ");}}}
AJAX asynchronous Form Verification
Prerequisite: Know how to configure AJAX.
Write a java class, write a method, receive the "user" object or user name (string type), and then call the dao layer (background) code to judge, you should know how to write the dao-layer code, then return the judgment result, and obtain the returned data on the JSP page, and then judge again.
Recommendation: Baidu source code or google Code