效果
导包
需要导入 jar包有:
下载地址:
链接:https://pan.baidu.com/s/1X0IEzRNMpKQG8ZmwX2jAKw 提取码:uyg6 复制这段内容后打开百度网盘手机App,操作更方便哦
页面代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html lang="zh"> <head> <meta charset="UTF-8"> <title>使用Ajax校验用户名是否可用</title> <script src="js/jquery-1.7.2.min.js"></script> </head> <body> <form> <input type="text" id="username" name="username" placeholder="请输入用户名"> <span id="span_username"></span> <br/> <input type="password" name="password" placeholder="请输入密码"><br> <input type="submit" value="戳我来注册"><br> </form> </body> </html> <script> //在页面加载完成后 $(function () { //给username绑定blur(失焦)事件 | 光标离开username区域后 $("#username").blur(function () { //获取username文本输入框的值 var username = $(this).val(); //发送ajax请求 //如果可用则显示:"此用户名太受欢迎,请更换一个" //如果不可用则:"用户名可用" $.get("showUserServlet",{username:username},function (data) { var span = $("#span_username"); if(data.userExsit){ //用户名存在 span.css("color","red"); span.html(data.msg); }else{ //用户名不存在 span.css("color","green"); span.html(data.msg); } }); }); }); </script>
Servlet代码:
package cn.javabs.web.servlet; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * 基于IDEA开发工具 | 并使用Servlet的3.0技术、可省略web.xml中映射代码的编写 *@author:Mr.yang * */ @WebServlet("/showUserServlet") public class ShowUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 设置响应的数据格式为json并且设置编码为utf-8 response.setContentType("application/json;charset=utf-8"); // 2. 获取用户名 String username = request.getParameter("username"); // 3. 调用service层判断用户名是否存在 Map<String,Object> map = new HashMap<String,Object>(); if("wangcai".equals(username)){ //若用户名为“wangcai”存在 map.put("userExsit",true); map.put("msg","此用户名太受欢迎,请更换一个"); }else{ //若用户名为“wangcai”不存在 map.put("userExsit",false); map.put("msg","用户名可用"); } // 4.将map转为json,并且传递给客户端 // 4.1 将map转为json ObjectMapper mapper = new ObjectMapper(); // 4.2 并且传递给客户端 mapper.writeValue(response.getWriter(),map); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 调用doPost方法,实现代码的复用性 this.doPost(request, response); } }
下载
代码托管: