利用SpringMVC框架,通过Ajax与jQuery实现网站登录用户名和密码的校验
首先,新建一个Maven项目
项目结构如下
导入JAR依赖
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-webmvc</artifactId> 5 <version>5.0.2.RELEASE</version> 6 </dependency> 7 8 <dependency> 9 <groupId>javax.servlet</groupId> 10 <artifactId>servlet-api</artifactId> 11 <version>2.3</version> 12 </dependency> 13 14 <dependency> 15 <groupId>javax.servlet.jsp</groupId> 16 <artifactId>javax.servlet.jsp-api</artifactId> 17 <version>2.3.3</version> 18 </dependency> 19 </dependencies>
Controller层
1 package com.lzp.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.GetMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 /** 8 * @Author LZP 9 * @Date 2021/6/26 13:21 10 * @Version 1.0 11 */ 12 @Controller 13 public class AjaxController { 14 15 @GetMapping("/toAjax") 16 public String toAjax() { 17 return "ajax"; 18 } 19 20 @GetMapping(value = "/check", produces = {"text/html; charset=utf-8", "application/json"}) 21 @ResponseBody 22 public String check(String username, String password) { 23 String msg = ""; 24 if (username != null) { 25 if ("admin".equals(username)) { 26 msg = "ok"; 27 } else { 28 msg = "用户名错误"; 29 return msg; 30 } 31 } 32 33 if (password != null) { 34 if ("123".equals(password)) { 35 msg = "ok"; 36 } else { 37 msg = "密码错误"; 38 return msg; 39 } 40 } 41 return msg; 42 } 43 44 }
注意:注解@GetMapping中除了提供一个请求的映射地址外,还要另外添加一个属性:produces = {"text/html; charset=utf-8", "application/json"},为了防止返回的json字符串乱码
ajax.jsp页面
1 <%-- 2 Created by IntelliJ IDEA. 3 User: 14715 4 Date: 2021/6/26 5 Time: 13:25 6 To change this template use File | Settings | File Templates. 7 --%> 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 9 <!DOCTYPE html> 10 <html lang="en"> 11 <head> 12 <meta charset="UTF-8"> 13 <title>Ajax</title> 14 <script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js" type="text/javascript"></script> 15 <script type="text/javascript"> 16 function check() { 17 loadData(); 18 } 19 20 function loadData() { 21 $.ajax({ 22 type: "GET", 23 url: "${pageContext.request.contextPath}/check", 24 data: { 25 "username" : $("[name='username']").val(), 26 "password" : $("[name='password']").val() 27 }, 28 success: function (data) { 29 console.log(data); 30 $("#msg").html(data); 31 // 设置css样式 32 if (data === 'ok') { 33 $("#msg").css("color", "green"); 34 } else { 35 $("#msg").css("color", "red"); 36 } 37 }, 38 error: function () { 39 40 } 41 }); 42 } 43 </script> 44 </head> 45 <body> 46 <div> 47 用户名:<input type="text" name="username" /><br> 48 密码:<input type="password" name="password" /><br/> 49 <button onclick="check()">校验</button> 50 <span id="msg"></span> 51 </div> 52 </body> 53 </html>
测试结果