1. jsp page
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>ajax验证用户名是否可用
2. web.xml
Java code
AjaxServlet com.servlet.AjaxServlet AjaxServlet /ajax
3. servlet
Java code
package com.servlet; 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 AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String userName = request.getParameter("userName"); if(userName.equals("admin")){ out.print("用户名已经存在"); } else if (userName.length() == 0) { out.print("用户不能为空"); } else if (userName.indexOf(" ") > 0) { out.print("用户不能含有空格"); } else if (userName.length() > 10 || userName.length() < 4) { out.print("用户长度在4-10之间"); } else { out.print("用户名可用"); } out.flush(); out.close(); } }