Springboot项目使用AJAX实现前端发送数据后台查询数据库并进行判断实现登录功能!

Springboot项目使用AJAX实现前端发送数据后台查询数据库并进行判断实现登录功能!

如果你还不会创建Springboot项目,点击这里
一,功能实现简介
从标题就能知道我们需要实现的是前端页面通过ajax发送数据到后台,然后后台进行逻辑处理并返回验证数据,这时前端判断返回的验证数据,做出相应的动作。

二,实现登录展示,先看效果再看具体代码实现
此时我的数据库UserInfo表中的数据,就只有一个,我们就只用这个测试。
在这里插入图片描述
1,用户输入数据与数据库中一致
此时输入用户名:gan 密码:123 登录成功
在这里插入图片描述
并返回到index.html
在这里插入图片描述
2,用户输入与数据库中不一致
这里用 用户名:gan 密码:12 举例,当然可以随便输入的
在这里插入图片描述
此时控制台还会打印提示,因为设置的
在这里插入图片描述

三,前端代码
这里分成HTML,js代码,因为我是分开写的,毫无保留的分享,啊哈哈
HTML

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>登录</title>
		<link rel="stylesheet" href="css/style.css">
		<script src="js/login.js"></script>
		<script src="http://code.jquery.com/jquery-latest.js"></script><!--支持ajax的文件库-->
	</head>
	<body class="loginbody">
		<div class="box">
			<h3>登录</h3>
			<from action="submit">
				<div class="inputbox">
					<input id="username" type="text"  placeholder="用户名">
					<!-- <label>Username</label> -->
				</div>
				<div class="inputbox">
					<input id="password" type="password" placeholder="密码">
					<!-- <label>Password</label> -->
				</div>
				<input type="button" onclick="login()" value="登录" />
			<!-- 	<div class="div" οnclick="login()">登录</div> -->
				<!-- <a href="index.jsp">登录</a> -->
				<a href="register.html">没有?注册</a>
				<a href="backPassword.html">找回密码</a>
			</from>
		</div>
	</body>
</html>

  //登录
function login() {
	// alert("hello");
	// var username = $("#username").val();
	var username =document.getElementById('username').value;
	// alert(username.id)
	if(null == username || "" == username) {
		alert("请输入用户名");
		return;
	}
	// var pwd = $("#password").val();
	var password =document.getElementById('password').value;
	if(null == password || "" == password) {
		alert("请输入密码");
		return;
	}
	//调用登录接口
	$.ajax({
	url : "http://localhost:8082/userLogin",
	type : "POST",
	data : {
		"username":username,
		"password":password
	},
	dataType : "json",//后台返回来的数据类型
	// ContentType: "application/json;charset=UTF-8",
	success : function(data) {
		//后台返回数据
		if (data.status == "ok") {
			alert(data.message);
			window.location.href = "index.html";
		}
		else {
			alert("用户名或密码错误,请仔细检查~~");    //登录失败
		}
	},
	error:function (errorThrown) {
		alert("用户名或密码错误!")
	}
});
}
	

四,后台代码
pojo实体类

package com.springboot.springboot.pojo;

import javax.persistence.*;
import java.time.LocalDateTime;

/**
 * @author ganxiang
 * IDE      IntelliJ IDEA
 * @project_name and filename Springboot UserInfo
 * @date 2020/04/08 0008 14:02
 */
@Entity
@Table(name = "UserInfo")
public class UserInfo {
    @Column(length = 16)
    private  String userName;
    @Column(length = 16)
    private String password;
    @Id
    @GeneratedValue
    private Integer id;//唯一标识符,自增
    @Column(columnDefinition = "timestamp default current_timestamp",insertable = false,updatable = false)
    private LocalDateTime insertTime;
    @Column(columnDefinition = "timestamp default current_timestamp  on update current_timestamp",insertable = false,updatable = false)
    private LocalDateTime updateTime;

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public Integer getId() {
        return id;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

dao层

package com.springboot.springboot.dao;

import com.springboot.springboot.pojo.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends JpaRepository<UserInfo, Integer> {
    //定义通过用户名密码查询数据
    public UserInfo findByUserNameAndPassword(String username,String password);
}

service层

package com.springboot.springboot.service;

import com.springboot.springboot.dao.UserDao;
import com.springboot.springboot.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl {
    @Autowired
    UserDao userDao;
    public UserInfo getUser(String name,String pwd){
        return userDao.findByUserNameAndPassword(name,pwd);
    }

}

controller层

package com.springboot.springboot.controller;

import com.springboot.springboot.pojo.UserInfo;
import com.springboot.springboot.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import com.alibaba.fastjson.JSON;

/**
 * @author ganxiang
 * IDE      IntelliJ IDEA
 * @project_name and filename Springboot UserController
 * @date 2020/04/08 0008 14:15
 */

@Controller
public class UserController {
    @Autowired
    UserServiceImpl userService;
    @RequestMapping("/userLogin")
    @ResponseBody
    public String userLogin(HttpServletRequest request, HttpSession session, @RequestParam Map<String, String> parameter) {
        //1,获取前端发送来的数据
        String name = request.getParameter("username");
        String pwd = request.getParameter("password");
        System.out.println(name + ":" + pwd);
        try {
            //2,通过前端参数来查询用户是否存在
            UserInfo user = userService.getUser(name, pwd);
            System.out.println(user.toString());
            //3,用户存在对返回的验证数据处理
            if (user != null) {
                session.setAttribute("userInfo", user);
                parameter.put("message", "欢迎登录");
                parameter.put("status", "ok");
            }
        } catch (Exception e) {
            //3,用户不存在对返回的验证数据处理
            System.out.println("用户名或密码错误~,请仔细检查哟~~");
            parameter.put("message", "用户名或密码错误");
            parameter.put("status", "no");
        }
        //4,将验证数据返回给前端
        return JSON.toJSONString(parameter);
    }

}


  • 8
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值