Ajax用户登录

后台

@Controller
public class AjaxController {	
//用户登录
	@RequestMapping("/login")
	@ResponseBody
	public Boolean login(String username,String password){
		System.out.println(username);
		System.out.println(password);
		if("admin".equals(username) && "123".equals(password)){
			return true;//登录成功
		}
		return false;
	}
}

两个前台页面:

1.登录成功后的页面:index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	恭喜你,登录成功!!!!!1
</body>
</html>

2.登录页面:login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	//返回Ajax对象 
	function getAjax() {
		if (XMLHttpRequest) {
			return new XMLHttpRequest();
		} else {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	function login() {
		//解决前台传值到后台为空
		var username = document.getElementById("username").value;
		var password = document.getElementById("password").value;
		
		//1.拿到Ajax对象
		var xhr = getAjax();
		//2.open:准备URL【解决参数传值问题】
		xhr.open("post","/login");
		//修改请求头(POST请求传参,必需加这一句,而且它的位置在open后面,send前面)
		xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		//3.监听对象状态变化,拿到返回数据
		xhr.onreadystatechange = function(){
			if(xhr.readyState==4&& xhr.status==200){
				var result = xhr.responseText;//返回的是一个字符串 "true","false"
				console.debug(result);
				if(result == "true"){
					window.location.href ="/index.jsp";//登录成功跳转到index页面
				}else{
					document.getElementById("erroLogin").innerHTML="用户名或密码错误,登录失败";
				}
			}
		}
		//4.发送请求
		//如果是POST请求,在send方法中发送数据
		xhr.send("username="+username+"&password="+password)
	}
</script>
</head>
<body>
	<form action="/checkName" method="post">
		用户名:<input type="text" name="username" id="username"/><br/>
		密码:<input type="password" name="password" id="password"/><br/>
		<input type="button" onclick="login();" value="登录">
		<span id="erroLogin"></span>
	</form>
</body>
</html>

===》效果展示图

猜你喜欢

转载自blog.csdn.net/qq_42217906/article/details/86300181
今日推荐