1.创建项目
2.引入前端代码并检查是否有误
3.定义接口
需求分析
对于后端开发⼈员⽽⾔, 不涉及前端⻚⾯的展⽰, 只需要提供两个功能
1. 登录⻚⾯: 通过账号和密码, 校验输⼊的账号密码是否正确, 并告知前端
2. ⾸⻚: 告知前端当前登录⽤⼾. 如果当前已有⽤⼾登录, 返回登录的账号, 如果没有, 返回空值
接⼝定义
1. 校验接⼝
请求路径:/user/login
请求⽅式:POST
接⼝描述:校验账号密码是否正确请求参数:
参数名 类型 是否必须 备注 userName String 是 校验的账号 password String 是 校验的密码 响应数据:
Content-Type: text/html
响应内容:true //账号密码验证成功
false//账号密码验证失败
2. 查询登录⽤⼾接⼝
请求路径:/user/getLoginUser
请求⽅式:GET
接⼝描述:查询当前登录的⽤⼾
请求参数:
⽆
响应数据:Content-Type: text/html
响应内容:
zhangsan
4.服务器代码
4.1 校验接口
package com.example.demo.controller;import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpSession;/*** Created with IntelliJ IDEA.* Description:* User: 吉祥瑞* Date: 2024-03-24* Time: 22:47*/
@RestController
@RequestMapping("/user")
public class LoginController {@RequestMapping("/login")public boolean login(String userName, String password, HttpSession session){//1.校验获取参数是否为空//StringUtils.hasLength() 是Spring提供的⼀个⼯具⽅法, 判断字符串是否有值//字符串为null或者""时, 返回false, 其他返回trueif(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){return false;}//2.校验session中是否有相应的数据if(userName.equals("userName")&&password.equals("password")){session.setAttribute("username",userName);return true;}return false;}
}
测试接口--利用postman
4.2 查询登录用户接口
@RequestMapping("/getLoginUser")public String getLoginUser(HttpSession session) {//从Session中获取⽤⼾登录信息String userName=(String) session.getAttribute("userName");//需要进行强转//如果⽤⼾已经登录, 则直接返回⽤⼾登录(session不为空)if (StringUtils.hasLength(userName)){return userName;}return "";}
测试成功
5.前后端交互
<!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({url: "/user/login",type: "post",data: {"userName": $("#userName").val(),"password": $("#password").val()},success: function(result){if(result){location.href = "/index.html"}else{alert("账号或密码有误,请重新输入")}}})}</script>
</body></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({url: "/user/getLoginUser",type: "get",success: function(result){$("#loginUser").text(result);}})</script>
</body></html>
成功!!!