Jsp 页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html> <head> <base href="<%=basePath%>"> <title>My JSP 'Demo1.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="js/jquery-3.0.0.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ $('#in').click(function(){ $.ajax({ type:"post", url:"login", async:true, data:{ name:$('#userNo').val(), }, success:function(data){ if (data=='0') { $('#show').html('<font color="red">用户名已存在</font>'); } else{ $('#show').html('<font color="green">用户名可用</font>'); } } }); }) }) </script> </head> <body> 用户名:<input id="userNo" type="text" /> <input id="in" type="button" value="登录" /> <div id="show"></div> </body></html>Servlet 页面
package com.jereh.servlet;
import java.io.IOException;
import java.io.PrintWriter;import java.util.Arrays;import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> names = Arrays.asList("aaa","bbb","ccc"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); if (names.contains(name)) { out.print("0"); } else { out.print("1"); } out.flush(); out.close(); }}