用户登录项目JAVA简单实现

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>

  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值