springboot+layui+mysql+Ajax实现用户登录
时间: 2023-05-26 12:03:38 浏览: 124
SpringBoot使用Ajax实现登录
实现用户登录,需要以下步骤:
1. 定义前端界面,使用layui搭建用户登录表单,包括用户名和密码的输入框,以及提交按钮。
2. 在后端使用Spring Boot框架搭建RESTful API接口,接收前端传来的用户名和密码,进行登录验证,返回登录结果。
3. 定义用户实体类,映射数据库表。
4. 使用MyBatis操作数据库,实现用户登录验证。
5. 将用户登录结果封装成Json格式,通过Ajax异步请求返回给前端界面。
以下是实现代码:
前端界面:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link href="https://cdn.jsdelivr.net/npm/layui@2.5.6/dist/css/layui.css" rel="stylesheet">
</head>
<body>
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md3"></div>
<div class="layui-col-md6" style="margin-top: 20px">
<form class="layui-form">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-inline">
<input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit lay-filter="login" style="width:100%;">登录</button>
</div>
</form>
</div>
<div class="layui-col-md3"></div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/layui@2.5.6/dist/layui.js"></script>
<script>
layui.use(['form', 'element'], function () {
var form = layui.form
var element = layui.element
//监听提交
form.on('submit(login)', function (data) {
$.ajax({
url: "/user/login",
type: "POST",
data: {
username: data.field.username,
password: data.field.password
},
success: function (result) {
if (result.code == 200) {
alert(result.msg)
//登录成功后跳转到其他页面
window.location.href = "/user/index";
} else {
alert(result.msg)
}
},
error: function () {
alert("服务器错误")
}
});
return false;
});
});
</script>
</body>
</html>
```
后端接口:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 登录验证接口
*/
@PostMapping("/login")
public Result login(String username, String password) {
//调用服务层进行登录验证
User user = userService.login(username, password);
if (user == null) {
return Result.fail("用户名或密码错误");
} else {
return Result.success("登录成功");
}
}
}
```
用户实体类:
```java
@Data
public class User {
private Integer id;
private String username;
private String password;
}
```
数据库操作类
```java
@Mapper
public interface UserMapper {
User getUserByUsername(String username);
}
```
用户服务类:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
/**
* 登录验证
*/
public User login(String username, String password) {
User user = userMapper.getUserByUsername(username);
if (user == null) {
return null;
}
if (!user.getPassword().equals(password)) {
return null;
}
return user;
}
}
```
阅读全文