When a user is registered, Ajax is required to asynchronously verify whether the user exists. The authentication information can be put in JSP or servlet class in Java, the difference between the two is that if we use JSP and Servlet for Web applications, the difference is the same. This also reflects the relationship between JSP and Servlet. The relationship between Servlet and JSP and the embodiment of this relationship in Tomcat are described here! Make a summary of Ajax technical knowledge before simply presenting and comparing their respective implemented code!
The main content of AJAX is as follows:
The main process of using Ajax includes 1. Creating an XMLHTTPRequest object, 2. Setting the sending back function, 3. specifying the information sending location, submission method, and Asynchronization. 4. Sending a request. The javascript code is as follows:
1: <script type="text/javascript">
2: var XMLHttpRequestIns = null;
3:
4: function AjaxF() {
5: // create an Ajax core object and PASS Parameters
6: CreateXMLHttpRequest();
7: // set parameters
8: xmlhttprequestins. onreadystatechange = handlestatechange; // you can specify the callback function.
9: // location of the retrieved content
10: XMLHttpRequestIns.open("GET", "XMLFile1.xml", true);
11: // send
12: XMLHttpRequestIns.send(null);
13: }
14: function CreateXMLHttpRequest() {
15: if (window.ActiveObject) {
16: XMLHttpRequestIns = new ActiveXObject("Microsoft.XMLHTTP");
17: }
18: else if(window.XMLHttpRequest )
19: {
20: XMLHttpRequestIns = new XMLHttpRequest();
21: }
22: }
23: // process the returned data
24: function handleStateChange() {
25: if (XMLHttpRequestIns.readyState == 4) {
26:
27: if (XMLHttpRequestIns.status == 200) {
28: Alert ("Server Message" + xmlhttprequestins. responsetext );
29: }
30: }
31: }
32: </script>
With this foundation, it is easy to use Ajax in Java EE to call JSP or servlet for processing. However, there are some minor differences between calling the two. This difference also comes from the relationship between JSP and servlet! The Code is as follows:
1. HTML code: Specify the verification method in the onblur method of the input. The span tag after the tag is used to display the prompt information (whether the tag exists) returned after Ajax verification)
1: <tr>
2: <td width="22%" height="29">
3: <div align="right">
4: <font color = "# ff0000"> * </font> User code: & nbsp;
5: </div>
6: </td>
7: <td width="78%">
8: <input name="userId" type="text" class="text1" id="userId"
9: size="10" maxlength="10" value="<%=userId %>" onblur
10: ="validate(this)"/><span id="userIdspan"></span>
11: </td>
12: </tr>
2. JavaScript code: the focus is to master the method for creating the XMLHttpRequest class in Ajax, and specify the JSP class or servlet class for processing the verification process (JSP class here, see the URL variable in validate (field) below, and then specify and compile the callback function. Here the anonymous function is used, but the compiled callback function is also put below for reference.
1: <script type="text/javascript">
2: var xmlHttp;
3:
4: function createXMLHttpRequest() {
5: // indicates that the current browser is not IE, such as Firefox
6: if(window.XMLHttpRequest){
7: xmlHttp = new XMLHttpRequest();
8: }else if(window.ActiveXObject){
9: xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
10: }
11: }
12:
13: function validate(field) {
14: if(trim(field.value).length != 0){
15: // create XMLHttpRequest
16: createXMLHttpRequest();
17: var url = "user_validate.jsp?userId=" + trim(field.value) + "×tamp=" + new Date().getTime();
18: //alert(url);
19: xmlHttp.open("GET",url,true);
20:
21: // method address. It is automatically called and called back after the processing is complete. Do not add parentheses. Otherwise, it will become called.
22: //xmlHttp.onreadystatechange = callback;
23: XMLHTTP. onreadystatechange = function () {// anonymous Function
24: If (XMLHTTP. readystate = 4) {// Ajax engine initialization successful
25: If (XMLHTTP. Status = 200) {// HTTP protocol successful
26: document.getElementById("userIdspan").innerHTML = "<font color='red'>" + xmlHttp.responseText + "</font>";
27: }else {
28: Alert ("request failed, error code =" + XMLHTTP. status );
29: }
30: }
31: };
32: // send the parameter to the Ajax engine, not the execution
33: xmlHttp.send(null);
34: }else {
35: document.getElementById("userIdspan").innerHTML = "";
36: }
37: }
38:
39: function callback () {// This is the callback function. However, in this Ajax application, the method of the above anonymous function is used if this method is not called.
40: If (XMLHTTP. readystate = 4) {// Ajax engine initialization successful
41: If (XMLHTTP. Status = 200) {// HTTP protocol successful
42: document.getElementById("userIdspan").innerHTML = "<font color='red'>" + xmlHttp.responseText + "</font>";
43: }else {
44: Alert ("request failed, error code =" + XMLHTTP. status );
45: }
46: }
47: }
48: </script>
3. the JSP or servlet class for the verification process specified by the variable URL in the validate (field) method above. jsp (user_validate.jsp) is listed here ).
1: <%@ page language="java" contentType="text/html; charset=GB18030"
2: pageEncoding="GB18030"%>
3: <%@ page import="com.bjpowernode.drp.sysmgr.manager.*" %>
4: <%
5: String userId = request.getParameter("userId");
6: if(UserManager.getInstance().findUserById(userId) != null) {
7: Out. println ("the user code already exists! ");
8: }
9: %>
4. The usermanager used in 3 is the class used to query the user based on the userid in the database. This is skipped!
5. Now Ajax calls JSP to process the verification code. If servlet is called for verification, the above variable URL must point to the servlet class, as shown below:
1: var url = "../servlet/uservalidateservlet? Usertid = "+ trim (field. value) + "& timestamp =" + new date (). gettime (); // Add a timestamp, which indicates that each URL is different and prevents caching.
6. Compare the verification process in servlet with Step 1 in the previous section. The Code is as follows:
1: public class UserValidateServlet extends HttpServlet {
2:
3: @Override
4: protected void service(HttpServletRequest request, HttpServletResponse response)
5: throws ServletException, IOException {
6: // set contenttype
7: response.setContentType("text/html; charset=GB18030");
8:
9: // get the code
10: String userId=request.getParameter("usertId");
11: // execute the query to determine whether the query exists
12: if(UserManager.getInstance().findUserByUserId(userId)!=null){
13: // prompt that this code exists
14: Response. getwriter (). Print ("the user code already exists! ");
15: }
16: }
17:
18: }
Comparison between 3 and 6 shows that the contenttype method is different (JSP is specified in the @ page command and servlet is specified in the response method. However, to use this servlet to complete the verification process, you also need to use the Web. xml file in the configuration mentioned in servlet-JSP relationship and its embodiment in Tomcat. The Code is as follows:
- <servlet> <servlet-name>ClientIdValidateServlet</servlet-name> <servlet-class>com.bjpowernode.drp.util.servlet.ClientIdValidateServlet</servlet-class> </servlet>- <servlet-mapping> <servlet-name>ClientIdValidateServlet</servlet-name> <url-pattern>/servlet/ClientIdValidateServlet</url-pattern> </servlet-mapping>
Through the above code, you can go to use Ajax in Java. There is no big difference between using Ajax in general web pages. The main thing is to master the usage of xmlhttmrequest! This article compares JSP and Servlet in Ajax applications!