1.大纲
2.index.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 <script type="text/javascript" src="jquery-3.2.1.min.js"></script> 9 <script type="text/javascript"> 10 $(function(){ 11 $(":input[name='userName']").change(function(){ 12 var val=$(this).val(); 13 val=$.trim(val); 14 if(val!=""){ 15 var url="${pageContext.request.contextPath}/ValidateUserName"; 16 var args={"userName":val,"time":new Date()}; 17 $.post(url,args,function(data){ 18 $("#message").html(data); 19 }) 20 } 21 }) 22 }) 23 </script> 24 </head> 25 <body> 26 <form action="" method="get"> 27 UserName<input type="text" name="userName"/><br> 28 <div id="message"></div><br><br> 29 <input type="submit" value="SUBMIT"/> 30 </form> 31 </body> 32 </html>
3.ValidateUserName.java
1 package servlets; 2 import java.io.IOException; 3 import java.util.Arrays; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class ValidateUserName extends HttpServlet{ 12 13 private static final long serialVersionUID = 1L; 14 15 @Override 16 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 17 List<String> userNames=Arrays.asList("A","B","C"); 18 String userName=request.getParameter("userName"); 19 String result=null; 20 if(userNames.contains(userName)) { 21 result="<font color='red'>改用户被用</font>"; 22 }else { 23 result="<font color='green'>改用户可以使用</font>"; 24 } 25 response.setContentType("text/html;charset=UTF-8"); 26 response.setCharacterEncoding("UTF-8"); 27 response.getWriter().print(result); 28 } 29 30 31 }
4.web.xml映射
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 <display-name>newDynamicProjectTest</display-name> 4 <servlet> 5 <servlet-name>ValidateUser</servlet-name> 6 <servlet-class>servlets.ValidateUserName</servlet-class> 7 </servlet> 8 9 <servlet-mapping> 10 <servlet-name>ValidateUser</servlet-name> 11 <url-pattern>/ValidateUserName</url-pattern> 12 </servlet-mapping> 13 </web-app>
5.效果