利用jQuery框架,封装了底层的Ajax异步技术,通过简单的方法调用即可实现。这篇博客是针对用户注册时出现的用户名重名问题的自动检测,利用的技术是Ajax异步传输。
register.jsp 注册显示页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <form action="login" method="post" id="myform"> <table align="center"> <tr> <td>用户名:</td> <td> <input type="text" name="name" id="username" title="用户名" /> <div id="message"></div> </td> </tr> <tr> <td>密码:</td> <td><input type="password" name="pwd" id="userpwd" title="密码" /> </td> </tr> <tr> <td>性别:</td> <td><input type="radio" name="sex" value="男" title="性别" />男 <input type="radio" name="sex" value="女" title="性别" />女</td> </tr> <tr> <td>年龄:</td> <td><input type="text" name="age" title="年龄" /> </td> </tr> <tr> <td>Email:</td> <td><input type="text" name="email" title="Email" /> </td> </tr> <tr> <td colspan="2" align="center"><input type="button" value="注 册" onclick="check()" /> <input type="reset" value="重 置" /></td> </tr> </table> </form> </body> <script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-3.2.1.js">UserServlet 逻辑处理Servlet类,用于对用户重名的判断以及响应处理结果的输出等。其中用于数据库检测重名的方法省略了(LoginDao.getInstance().checkUserName(userName.trim()); // 查找数据库是否存在该用户名)
package com.servlet.user; 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; import com.dao.LoginDao; import com.user.UserInfo; public class UserServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); // 设置响应结果的格式为text/html,字符集为UTF-8 response.setCharacterEncoding("UTF-8"); // 设置响应结果的字符编码为UTF-8 // 禁止缓存 response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate"); response.setHeader("Cache-Control", "post-check=0,pre-check=0"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); PrintWriter out = response.getWriter(); out.println("<"1.0\" encoding=\"utf-8\""); // 从httpRequest()方法中获得请求参数值 // 通过httpRequest()方法封装的请求参数被编码为UTF-8格式,此处若想还原原来的编码格式,则需要通过UTF-8格式解码 String userName = request.getParameter("userName"); String result = null; boolean check = LoginDao.getInstance().checkUserName(userName.trim()); // 查找数据库是否存在该用户名 if (check) { result = "<font color='red'>该用户已经被使用</font>"; } else { result = "<font color='green'>该用户名可以使用</font>"; } response.getWriter().print(result); // 将结果输出到response响应流中 } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。