In this case, jQuery and Servlet technologies are used to determine whether the user name exists, so that readers can understand how jQuery calls the server background. It also provides solutions to solve Chinese garbled characters and how to avoid cache of various browsers. Functions:
If the user name is blank, the system prompts "the user name cannot be blank"
If the user name prompts "user name [xxxxxx] already exists, use another user name, 4"
If the user name does not exist, the message "user name [xxxxxx] does not exist, you can use this user name to register, 5"
The running effect is as follows:
Directory structure: server-side AjaxServer
The Code is as follows:
Package com. ljq. test;
Import java. io. IOException;
Import java. io. PrintWriter;
Import java.net. URLDecoder;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
@ SuppressWarnings ("serial ")
Public class AjaxServer extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Try {
// Set page UTF-8 encoding
Response. setContentType ("text/html; charset = UTF-8 ");
PrintWriter out = response. getWriter ();
Integer total = (Integer) request. getSession (). getAttribute ("total ");
Int temp = 0;
If (total = null ){
Temp = 1;
} Else {
Temp = total. intValue () + 1;
}
Request. getSession (). setAttribute ("total", temp );
// 1. Take the Parameter
String param = request. getParameter ("name ");
String name = URLDecoder. decode (param, "UTF-8 ");
// 2. Check whether the parameter is valid
If (param = null | param. length () = 0 ){
Out. println ("the user name cannot be blank ");
} Else {
// 3. Verification
If (name. equals ("linjiqin ")){
// 4. Return result data
Out. println ("username [" + name + "] already exists. Please use another username," + temp );
} Else {
Out. println ("user name [" + name + "] does not exist. You can use this user name to register," + temp );
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
}
@ Override
Protected void doPost (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
DoGet (request, response );
}
}
Configure web. xml
The Code is as follows:
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
AjaxServer
Com. ljq. test. AjaxServer
AjaxServer
/Servlet/ajaxServer
Index. jsp
Index. jsp page
The Code is as follows:
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>
My JSP 'index. jsp 'starting page