1、“zhangsan”.equals(userName) 把常量放在前面是为了防止空指针、
2、session不用我们担心会不会空指针,如果为null会为我们创建个空的session
3、网页清缓存
(1)ctrl+F5
(2)ctrl+shift+delete
4、后端清缓存
(1)maven 的clean
5、java代码
package com.example.demo.demos.web;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/login")
public class loginController {
@RequestMapping("/check")
public boolean check(String userName, String password, HttpSession session){
if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
return false;
}
if("zhangsan".equals(userName)&& "123456".equals(password)){
session.setAttribute("userName",userName);
return true;
}
return false;
}
@RequestMapping("/index")
public String index(HttpSession session){
String userName=(String) session.getAttribute("userName");
return userName;
}
}
6、html代码(login.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>用户登录</h1>
用户名:<input name="userName" type="text" id="userName"><br>
密码:<input name="password" type="password" id="password"><br>
<input type="button" value="登录" onclick="login()">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
function login() {
$.ajax({
type:"post",
url:"/login/check",
data:{
userName:$("#userName").val(),
password:$("#password").val()
},
success:function(result){
if(result==true){
location.href="index.html";
}else{
alert("用户名或密码错误!");
}
}
});
}
</script>
</body>
</html>
7、index.html代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>用户登录首页</title>
</head>
<body>
登录人: <span id="loginUser"></span>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$.ajax({
type:"get",
url:"/login/index",
success:function(result){
$("#loginUser").text(result);
}
});
</script>
</body>
</html>