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>
相关推荐
侠客行03174 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪4 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚6 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎6 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码6 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚6 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂7 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang7 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐7 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG7 小时前
JavaTuples 库分析
java