package com.ghj.packagofserlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxCheckUserNameServlet extends HttpServlet { private static final long serialVersionUID = 6387744976765210524L; /** * 处理demo1.jsp中异步验证 * * @author GaoHuanjie */ public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { try{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //System.out.println(1/0);//故意出现异常,以检查demo1.jsp中xmlHttpRequest.status!=200的分支语句是否可用 String userName=request.getParameter("userName");//获取“用户名” System.out.println("处理demo1.jsp中异步验证,用户名为:"+userName); if ("admin".equals(userName)) { out.print("1");//“1”表示用户名不可用。 } else { out.print("2");//“2”表示用户名可用。 } out.flush(); out.close(); }catch (Exception e) { e.printStackTrace(); response.setStatus(405); } } /** * 处理demo2.jsp中异步验证 * * @author GaoHuanjie */ public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { try{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //System.out.println(1/0);//故意出现异常,以检查demo2.jsp中xmlHttpRequest.status!=200的分支语句是否可用 String userName=request.getParameter("userName");//获取“用户名” System.out.println("处理demo2.jsp中异步验证,用户名为:"+userName); if ("admin".equals(userName)) { out.print("1");//“1”表示用户名不可用。 } else { out.print("2");//“2”表示用户名可用。 } out.flush(); out.close(); }catch (Exception e) { e.printStackTrace(); response.setStatus(405); } } }
代码5web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee " version="2.5"> <servlet> <servlet-name>AjaxCheckUserNameServlet</servlet-name> <servlet-class>com.ghj.packagofserlet.AjaxCheckUserNameServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxCheckUserNameServlet</servlet-name> <url-pattern>/AjaxCheckUserNameServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
以上就是使用传统方法实现异步校验的详细代码,希望对大家的学习有所帮助。
您可能感兴趣的文章: