一、页面代码
<!DOCTYPE html> <html> <head> <title>MyHtml.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=UTF-8"> <body> <table> <tr> <td>Login:</td> <td><input id="username" type="text" name="login"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" id="password"></td> </tr> <tr> <td colspan="2"><input type="submit"></td> </tr> </table> </body> </html>
二、jQuery代码
// 导入jQuery<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#username").keyup(function() { var value = $(this).val(); var strData = "username=" + value; $.ajax({ url : "MyServlet1", type : "get", //data : {"username":value}, // json格式 data: strData, dataType : "text", success : function(data, strStatus, xhr) { if (data == "已使用") $("#username").css("border-color", "red"); else $("#username").css("border-color", "green"); }, error : function(xhr, strStatus, strError) { alert(strError); } }); }); }); </script>
三、servlet代码
package com.yh.myServlet; 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 MyServlet1 extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String userName = request.getParameter("username"); System.out.println(userName); if (userName.equals("yh")) { out.print("已使用"); } else { out.print("可使用"); } } }
四、配置servlet
<servlet> <servlet-name>MyServlet1</servlet-name> <servlet-class>com.yh.myServlet.MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet1</servlet-name> <url-pattern>/Pages/MyServlet1</url-pattern> </servlet-mapping>
注:这个Pages是根据html页面的路径设置的
原文地址:https://www.cnblogs.com/YeHuan/p/10993905.html
时间: 2024-11-13 10:10:19