登录html
<form method="post" class="form-validate">
<div class="form-group">
<input id="login-username" type="text" name="loginUsername" required data-msg="Please enter your username" class="input-material">
<label for="login-username" class="label-material">User Name</label>
</div>
<div class="form-group">
<input id="login-password" type="password" name="loginPassword" required data-msg="Please enter your password" class="input-material">
<label for="login-password" class="label-material">Password</label>
</div><a id="login" class="btn btn-primary" onclick="login()">Login</a>
<!-- This should be submit button but I replaced it with <a> for demo purposes-->
</form>
登录js
function login() {
var username = document.getElementById("login-username").value //获取文本框的内容;
var password = document.getElementById("login-password").value
username = username.toString()
password = password.toString()
console.log(password)
$.ajax({
type:"POST",
url:"Login",
data:{
username:username,
password:password,
},
dataType:"json",
success:function(result){
if ( result.state == 200)
{
self.location='index.html'
}
else alert(result.error)
},
error:function(result){
alert('服务器连接错误')
}
})
}
java serlvet
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String uname = request.getParameter("username");
String pwd = request.getParameter("password");
JSONObject jsonObject = new JSONObject();
if (uname.equals("admin")&&pwd.equals("admin")){
//创建session对象
HttpSession session = request.getSession();
//把用户数据保存在session域对象中
session.setAttribute("uname", uname);
jsonObject.put("state", "200");
System.out.println(jsonObject.toString());
out.print(jsonObject.toString());
}
else{
System.out.println(uname);
jsonObject.put("state", "404");
jsonObject.put("error", "请输入正确的账号和密码!");
System.out.println(jsonObject.toString());
out.print(jsonObject.toString());
}
注销serlvet
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
JSONObject jsonObject = new JSONObject();
HttpSession session = request.getSession(false);//防止创建Session
session.invalidate();
jsonObject.put("state", "200");
jsonObject.put("error", "注销成功!");
System.out.println(jsonObject.toString());
out.print(jsonObject.toString());