时间:2021-07-01 10:21:17 帮助过:6人阅读
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; %>如何使用传统方法异步验证用户名的唯一性
代码2demo1.jsp文件:
代码3demo2.jsp文件:
代码4AjaxCheckUserNameServlet.java文件:
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"?>AjaxCheckUserNameServlet com.ghj.packagofserlet.AjaxCheckUserNameServlet AjaxCheckUserNameServlet /AjaxCheckUserNameServlet index.jsp
以上就是使用传统方法实现异步校验的详细代码,希望对大家的学习有所帮助。