Mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
MySQL依赖
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>2.3.1</version>
<scope>test</scope>
</dependency>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
spring:
datasource:
url: jdbc:mysql://你的数据库连接:3306/数据库名字?useUnicode=true&characterEncoding=utf-8
username: 用户名
password: 密码
driver-class-name: com.mysql.cj.jdbc.Driver
CREATE TABLE `kfm_user` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',
`username` varchar(32) NOT NULL COMMENT '用户名',
`password` varchar(32) NOT NULL COMMENT '密码',
`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',
`create_time` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
package com.kaifamiao.userserach;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity implements Serializable {
private Long id;
private String username;
private String password;
private Byte status;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Date createTime;
}
@Select("SELECT * FROM kfm_user WHERE username = #{username}")
package com.kaifamiao.userserach;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("SELECT * FROM kfm_user WHERE username = #{username}")
UserEntity findByName(@Param("username") String username);
}
package com.kaifamiao.userserach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public UserEntity getUserByName(String username) {
return userMapper.findByName(username);
}
}
a、控制器返回标准json格式
如果用户存在
{
"code": "200",
"message": "user exists.",
"status": "success"
}
如果用户不存在
{
"code": "250",
"message": "user does not exist.",
"status": "error"
}
getUserByName(String username)
package com.kaifamiao.userserach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/userserach")
public Map<String, Object> getUserByName(String username) {
System.out.println("getUserByName"+username+"====================");
UserEntity user =userService.getUserByName(username);
Map<String, Object> response = new HashMap<>();
if (user == null) {
response.put("code", "250");
response.put("status", "error");
response.put("message", "user does not exist.");
}
if(user!=null){
response.put("code", "200");
response.put("status", "success");
response.put("message", "user exists.");
}
return response;
}
}
@MapperScan("com.kaifamiao.userserach")
package com.kaifamiao.userserach;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.kaifamiao.userserach")
public class UserserachApplication {
public static void main(String[] args) {
SpringApplication.run(UserserachApplication.class, args);
}
}
到这里后端部分已经完成
@GetMapping("/login")
public ModelAndView loginview() {
return new ModelAndView("login");
}
注意,html页面放在resources/templates/下面
参考:https://layui.dev/docs/2/form/#login
原始页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
<link href="//unpkg.com/layui@2.8.18/dist/css/layui.css" rel="stylesheet">
</head>
<body>
<style>
.demo-login-container{width: 320px; margin: 21px auto 0;}
.demo-login-other .layui-icon{position: relative; display: inline-block; margin: 0 2px; top: 2px; font-size: 26px;}
</style>
<form class="layui-form">
<div class="demo-login-container">
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-username"></i>
</div>
<input type="text" name="username" value="" lay-verify="required" placeholder="用户名" lay-reqtext="请填写用户名" autocomplete="off" class="layui-input" lay-affix="clear">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-password"></i>
</div>
<input type="password" name="password" value="" lay-verify="required" placeholder="密 码" lay-reqtext="请填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
</div>
</div>
<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<div class="layui-input-wrap">
<div class="layui-input-prefix">
<i class="layui-icon layui-icon-vercode"></i>
</div>
<input type="text" name="captcha" value="" lay-verify="required" placeholder="验证码" lay-reqtext="请填写验证码" autocomplete="off" class="layui-input" lay-affix="clear">
</div>
</div>
<div class="layui-col-xs5">
<div style="margin-left: 10px;">
<img src="https://www.oschina.net/action/user/captcha" onclick="this.src='https://www.oschina.net/action/user/captcha?t='+ new Date().getTime();">
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<input type="checkbox" name="remember" lay-skin="primary" title="记住密码">
<a href="#forget" style="float: right; margin-top: 7px;">忘记密码?</a>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">登录</button>
</div>
<div class="layui-form-item demo-login-other">
<label>社交账号登录</label>
<span style="padding: 0 21px 0 6px;">
<a href="javascript:;"><i class="layui-icon layui-icon-login-qq" style="color: #3492ed;"></i></a>
<a href="javascript:;"><i class="layui-icon layui-icon-login-wechat" style="color: #4daf29;"></i></a>
<a href="javascript:;"><i class="layui-icon layui-icon-login-weibo" style="color: #cf1900;"></i></a>
</span>
或 <a href="#reg">注册帐号</a>
</div>
</div>
</form>
<!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
<script src="//unpkg.com/layui@2.8.18/dist/layui.js"></script>
<script>
layui.use(function(){
var form = layui.form;
var layer = layui.layer;
// 提交事件
form.on('submit(demo-login)', function(data){
var field = data.field; // 获取表单字段值
// 显示填写结果,仅作演示用
layer.alert(JSON.stringify(field), {
title: '当前填写的字段值'
});
// 此处可执行 Ajax 等操作
// …
return false; // 阻止默认 form 跳转
});
});
</script>
</body>
</html>
在用户名填入后给一个请求到刚才写的控制器
如果用户存在
{
"code": "200",
"message": "user exists.",
"status": "success"
}
如果用户不存在
{
"code": "250",
"message": "user does not exist.",
"status": "error"
}
fetch(
/user/userserach?username=${encodedUsername}
在layui里添加事件
layui.$("input[name='username']").blur(function () {
})
layui.$到本质其实是jQuery事件
var username = layui.$("input[name=’username’]").val()
layui.("input[name='username']").blur(function () {
console.log("开始查询");
var username = layui.("input[name='username']").val()
console.log(username);
var encodedUsername = encodeURIComponent(username);
fetch(`/user/userserach?username={encodedUsername}`, {
method: 'GET',
})
.then((response) => response.json())
.then((data) =>{
console.log(data)
console.log(data.code)
if(data.code === "200"){
layer.msg("用户存在");
layui.("input[name='username']").val('')
return false;
}
});
});
layer.msg("用户存在");可以用其他方式
十四、总结
这个程序关键就在于获取文本框输入后,马上通过blur事件向服务器端发送请求,然后拿到回传到值。
powered by kaifamiao