spring MVC 简单的案例(2)用户登录

一、用户登录

1)前端代码

index.html

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>

</script>
</body>

</html>

login.html

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() {
    
    }

  </script>
</body>

</html>

运行服务,打开浏览器,查看前端页面是否正常

2)需求分析

在登录页面login.html,输入用户名 和 密码 之后

会返回用户名到首页index.html

2-1接口定义 - 用户验证

/login/check

参数

userName

password

响应

用户和密码是否正确

true : 用户名和密码正确

false:用户或者密码错误

2-2接口定义 - 获取登录的用户

/login/index

参数

响应

登录的用户名

3)编写后端代码

java 复制代码
package com.ameris.springmvcdemo;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @ResponseBody
    @RequestMapping("/check")
    public boolean check(String userName, String password, HttpSession session){
        //1.校验账号 和 密码 是否为空
        //传统的方式
//        if(userName == null ||"".equals(userName)||password == null ||"".equals(password)){
//            return false;
//        }
        //spring提供的方式
        if (!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            return false;
        }

        //2.校验 用户 和 密码 是否正确
        //假设用户 和 密码是 zhangsan 123456
        if ("zhangsan".equals(userName) && "123456".equals(password)){
            //登录成功,要设置session
            session.setAttribute("userName",userName);
            return true;
        }
        return false;
    }
    @ResponseBody
    @RequestMapping("/index")
    public String index(HttpSession session){
        String userName = (String) session.getAttribute("userName");
        return userName;

    }
}

测试后端代码,后端没问题

测试浏览器,发现点击登录按钮无效,没有响应

查看前端代码

发现 js里这个login()这个函数没有写,所以点击登录按钮时没有效果

再次浏览器验证

发现跳转了到index.html这个页面了,但是没有显示登陆人的名字

于是再查看 index.html 的前端页面代码

发现没有该页面的响应内容,写上js代码

再次测试

现在显示 用户名了

假设输入个错误密码

也可以正确提示

注意

data里面的参数名 要与 后端的参数名 保持一致,否则前端的数据无法正确传递到后端

例如我故意把userName 写错成 Name

即便我输入正确的用户名密码,还是提示我错误

查看日志

发现userName 为空,说明该数据没有正确传递到后端来

所以在前端参数名这里一定要注意

4)完整的前端代码

login.html

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()">
  <!-- 当登录按钮点击后,会执行 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 和 password 是与后端定义的参数名对应
          //如果这里参数名 与 后端 不一致,那么会导致,这个数据无法正确传递到后端
          userName: $("#userName").val(),//$("#userName") 通过id名 userName这个标签,.val()获取该标签里的值,如果val("")里面有值,就是赋值
          password: $("#password").val()
        },
        success: function (result) {
          //sucess是一个回调函数,上述执行成功后,会执行这个函数
          //result 根据后端返回结果,是一个布尔类型的值
          if (result == true) {
            //用户名和密码正确
            //下面这几种跳转方式都可以
            location.href = "index.html";
            // location.assign("index.html");
            // location.replace("index.html");
          } else {
            alert("用户名或密码错误!!")
          }
        }
      });
    }

  </script>
</body>

</html>

index.html

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) {
                //result 根据后端返回结果,是一个用户名 userName
                $("#loginUser").text(result);
                //$("#loginUser") 选择 id 为 loginUser 的标签
                //.text(result); 标签里的内容 放置为 result
            }
        })
    </script>
</body>

</html>
相关推荐
xieliyu.6 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
明夜之约6 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee6 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs6 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司6 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
fangdengfu1237 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD7 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏7 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32
unicrom_深圳市由你创科技7 小时前
基于Spring AI框架的RAG应用
人工智能·spring·机器学习
Jinkxs8 小时前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链