. 1 Jsp Part: 2
. 3 <! - introduction of jquery js external file ->
. 4 < Script type = "text / JavaScript" the src = "js / jquery-3.1.1.min.js" > </ Script >
. 5 < Script >
. 6 $ ( function () {
. 7 // define global variables, there is only one label, label all selectors
. 8 var Lab = $ ( " label " );
. 9 lab.css ( " Color " , " Red " );
10 lab.css ( " font-size " , " 12px " );
. 11
12 is // click a button input any label will be performed, this test only a
13 is $ ( " : button " ) .click ( function () {
14 // Get the specified id first element content
15 var name = $ ( " #username " ) .val ();
16 // perform Ajax
. 17 $ .ajax ({
18 is // transmission type, used herein Post
. 19 type: " Post ",
20 // transport address, this is an indirect path, the path test in the same directory
21 is URL: " Search " ,
22 is // transmission data, through traditional values may be a question mark, such as URL: "? Search name =" name +
23 is Data: {name: name},
24 // successful execution
25 success: function (Mess) {
26 is // message feedback is "Yes"
27 IF (Mess == " Yes " ) {
28 // label label assignment
29 Lab .text ( " this user name already exists! " );
30 }else {
31 lab.text("用户名可以使用!");
32 }
33 }
34 })
35 })
36
37 })
38 </script>
39
40 </head>
41 <body>
42
43 <input type="text" id="userName" /><label></label><br/><br/>
44 <input type="button" id="accept" value="验证用户名"/>
45
46 </body>
1 Servlet部分:
2
3 @WebServlet("/search")
4 public class searchServlet extends HttpServlet {
5 private static final long serialVersionUID = 1L;
6
7 //get请求方式也传递给post处理
8 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
9 doPost(request, response);
10 }
11
12 protected voidthe doPost (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException {
13 is // avoid coding disorder. 8-uniform use UTF
14 Request.setCharacterEncoding ( "UTF-. 8" );
15 the response.setContentType ( "text / HTML; charset = . 8-UTF " );
16 // get content obtained from the jump page
. 17 String name = request.getParameter (" name " );
18 is the PrintWriter OUT = response.getWriter ();
. 19
20 is // assumed here as verification silly present, if desired, the actual test data, may find the operation from the database by jdbc
21 is IF (name.equals ( "Silly" )) {
22 is //Feedback information to the Ajax
23 is Out.print ( "Yes" );
24 } the else {
25 Out.print ( "NO" );
26 is }
27 }
28 }