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>
相关推荐
草履虫建模19 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
qq_2975746721 小时前
【实战教程】SpringBoot 实现多文件批量下载并打包为 ZIP 压缩包
java·spring boot·后端
老毛肚21 小时前
MyBatis插件原理及Spring集成
java·spring·mybatis
学嵌入式的小杨同学21 小时前
【Linux 封神之路】信号编程全解析:从信号基础到 MP3 播放器实战(含核心 API 与避坑指南)
java·linux·c语言·开发语言·vscode·vim·ux
lang201509281 天前
JSR-340 :高性能Web开发新标准
java·前端·servlet
Re.不晚1 天前
Java入门17——异常
java·开发语言
缘空如是1 天前
基础工具包之JSON 工厂类
java·json·json切换
追逐梦想的张小年1 天前
JUC编程04
java·idea
好家伙VCC1 天前
### WebRTC技术:实时通信的革新与实现####webRTC(Web Real-TimeComm
java·前端·python·webrtc
南极星10051 天前
蓝桥杯JAVA--启蒙之路(十)class版本 模块
java·开发语言