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>
相关推荐
虫小宝几秒前
企业微信API接口对接中Java后端的模拟测试(Mock)与单元测试实战技巧
java·单元测试·企业微信
Tim_Van3 分钟前
彻底解决:80 端口 GET/POST 正常,PUT 却报 ERR_CONNECTION_RESET?
java·vue.js·spring boot·ruoyi·若依
元媛媛5 分钟前
UiPath |5个基础自动化场景
android·java·自动化
独自破碎E7 分钟前
Spring AI怎么实现结构化输出?
java·人工智能·spring
h7ml7 分钟前
企业微信API接口对接系统中Java后端的持续集成/持续部署(CI/CD)落地技巧
java·ci/cd·企业微信
星火开发设计8 分钟前
C++ multimap 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识
码农水水12 分钟前
阿里Java面试被问:RocketMQ的消息轨迹追踪实现
java·开发语言·windows·算法·面试·rocketmq·java-rocketmq
APIshop16 分钟前
实战解析:1688详情api商品sku、主图数据
java·服务器·windows
醇氧21 分钟前
【maven】maven-site-plugin 插件
java·log4j·maven