The previous article discussed the theory of Ajax technology. This article discussed how to use XMLHttpRequest to asynchronously send GET requests to the server in actual programming without considering Chinese characters, chinese Garbled text will be discussed in subsequent articles! Here, we take a form registration process as an example to explain the Ajax process. For the sake of simplicity, the user name is not verified in the actual database. Here we simply think that as long as the user name is "Tom ", it indicates that you have already registered the account. You must change the user name to another one. Once the focus of the User Name text box is lost, Ajax starts to send requests.
First look at the file directory structure of the sample project:
Register. jsp:
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
Login. jsp:
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
Web. xml:
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>UsernameServlet</servlet-name> <servlet-class>web.UsernameServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UsernameServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
Usernameservlet. Java:
public class UsernameServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String uri=request.getRequestURI();String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));PrintWriter pw=response.getWriter();if(path.equals("/valiusername")){String username=request.getParameter("username");if(username.equals("tom")){pw.println("username exists,change one...");}else{pw.println("OK");}}if(path.equals("/register")){String username=request.getParameter("username");String password=request.getParameter("password");response.sendRedirect("login.jsp");}}}