登录注册--前后端分离(前后端代码)

本文详细介绍了使用layui框架实现前端的登录与注册功能,涉及数据库操作和后端Java Servlet的交互,包括管理员、用户和企业三种角色的验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现登录与注册

需要引入layui框架
–数据库课程设计–

根目录

在这里插入图片描述

1.登录

登录页面
在这里插入图片描述
前端代码(样式就不贴了,copy的)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    
<link rel="stylesheet" href="layui/css/layui.css" media="all">
</head>
<body>

    <div class="login-form">
        <h1 style="font-size:30px;font-weight: bolder">登 录</h1>
        <div id="radios">
            <input type="radio" name="choice" value="1" checked="checked">管理员 <!--默认选中-->
            <input type="radio" name="choice" value="2" >用户
            <input type="radio" name="choice" value="3" >企业
        </div>
        <div class="txtb">
            <input type="text" class="txtbinput" name="account" id="ac">
            <span data-placeholder="账号"></span>
        </div>

        <div class="txtb">
            <input type="password"class="txtbinput" name="password" id="pw">
            <span data-placeholder="密码"></span>
        </div>

        <input type="submit" class="logbtn" value="登 录" id='sbtn'>

        <div class="bottom-text">
            没有账号? <a href="reg.html">注册</a>
        </div>
        
    </div>
    <script src="layui/layui.js"></script>
    <script type="text/javascript">
    layui.use([ 'form', 'jquery', 'table' ], function() {
    	var form = layui.form;
    	var $ = layui.jquery;
    	$("#sbtn").click(function(){
    		 var id=[];
   		  $("input[name='choice']:checked").each(function(){//通过遍历获取多选框的值
   		    id.push($(this).val());
   		  });
   		  var senddata={"account":$("#ac").val(),"password":$("#pw").val(),"choice":id[0]};
    		console.log(senddata);
    		 $.ajax({
    	          url : 'LoginServlet',
    	          type : 'post',
    	          dataType : 'json',
    	          data :senddata,     
    	          success : function (data1) {
    	        	  console.log(data1);
    				if(data1.result=="manager"){window.location.href="index.html?myaccount="+$("#ac").val()+"&type=m";}
    				else if(data1.result=="employee"){window.location.href="index.html?myaccount="+$("#ac").val()+"&type=e";}
    				else if(data1.result=="company"){window.location.href="index.html?myaccount="+$("#ac").val()+"&type=c";}
    				else{layer.alert('密码错误', {icon: 2});}
    			},
    			error:function(err){
    				layer.alert('账号不存在', {icon: 2});}
    	})
    })
    })
    
    
        var txt=document.getElementsByClassName("txtbinput");
        for(var i=0;i<=1;i++){
            txt[i].onfocus=function(){
            this.className="focus";
        }
        txt[i].onblur=function(){
            if(this.value == "")
            this.classList.remove("focus");
        }
        }
        
       
    </script>

</body>
</html>

后端
LoginServlet

package com.cqust.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqust.biz.CompanyBiz;
import com.cqust.biz.EmployeeBiz;
import com.cqust.biz.ManagerBiz;
import com.cqust.entity.CompanyEntity;
import com.cqust.entity.EmployeeEntity;
import com.cqust.entity.ManagerEntity;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/pages/addUser.jsp");
		rd.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		// 1 获取页面参数信息
		String choice = request.getParameter("choice");
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String str = null;
		int flag = 0;
		if (choice.equals("1")) {
			// 2 调用业务处理逻辑
			ManagerBiz mBiz = new ManagerBiz();
			ManagerEntity manager = mBiz.selectManager(account);
			// 3 返回处理结果 给 页面
			if (manager != null) {
				flag = 1;// 存在
				response.setContentType("text/html;charset=utf-8");
				if (password.equals(manager.getMpassword())) {// 密码正确
					str = "{'result':'manager'}";
				} else {// 错误
					str = "{'result':'wrong'}";
				}
			}
		} else if (choice.equals("2")) {
			EmployeeBiz eBiz = new EmployeeBiz();
			EmployeeEntity employee = eBiz.selectEmployee(account);
			if (employee != null) {
				flag = 1;// 存在
				response.setContentType("text/html;charset=utf-8");
				if (password.equals(employee.getEpassword())) {// 密码正确
					str = "{'result':'employee'}";
				} else {// 错误
					str = "{'result':'wrong'}";
				}
			}
		} else if (choice.equals("3")) {
			CompanyBiz cBiz = new CompanyBiz();
			CompanyEntity company = cBiz.selectCompany(account);
			if (company != null) {
				flag = 1;// 存在
				response.setContentType("text/html;charset=utf-8");
				if (password.equals(company.getCpassword())) {// 密码正确
					str = "{'result':'company'}";
				} else {// 错误
					str = "{'result':'wrong'}";
				}
			}
		}
		if (flag == 1) {
			JSONObject jsonObject = JSONObject.parseObject(str);
			String json = JSON.toJSONString(jsonObject);
			System.out.println(json);
			out.write(json);
		} else {
			System.out.println("no");
			out.write("no");
		}
		out.flush();
		out.close();
	}
}

ManagerEntity代码:

package com.cqust.entity;

public class ManagerEntity {
	private String maccount;
	private String mpassword;
	public String getMaccount() {
		return maccount;
	}
	public void setMaccount(String maccount) {
		this.maccount = maccount;
	}
	public String getMpassword() {
		return mpassword;
	}
	public void setMpassword(String mpassword) {
		this.mpassword = mpassword;
	}
	public ManagerEntity(String maccount, String mpassword) {
		super();
		this.maccount = maccount;
		this.mpassword = mpassword;
	}
	public ManagerEntity() {
		super();
		// TODO Auto-generated constructor stub
	}
	
}

ManagerBiz代码:

package com.cqust.biz;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.cqust.dao.ManagerDao;
import com.cqust.entity.EmployeeEntity;
import com.cqust.entity.ManagerEntity;

public class ManagerBiz {
	private static ManagerDao dao = new ManagerDao();
	
	public ManagerEntity selectManager(String account) {//查询单个
		ManagerEntity manager=new ManagerEntity();
		try {
			manager=dao.selectManager(account);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return manager;
	}
	
	public List selectAllManagers() {//查询所有
		List<ManagerEntity> list = new ArrayList<ManagerEntity>();
		try {
			list=dao.selectAllManagers();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public Boolean insertManager(ManagerEntity Manager) {//插入
		Boolean res=null;
		try {
			res=dao.insertManager(Manager);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public Boolean deleteManager(String account) {//删除
		Boolean res=null;
		try {
			res=dao.deleteManager(account);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}
	
	public Boolean updateManager(ManagerEntity Manager) {//修改
		Boolean res=null;
		try {
			res=dao.updateManager(Manager);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}
}

ManagerDao代码:

package com.cqust.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.cqust.entity.ManagerEntity;
import com.cqust.util.C3p0Utils;

public class ManagerDao {
	    // 查询所有管理员,返回List集合
		public List selectAllManagers() throws SQLException {
			QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
			String sql = "select * from manager";
			List list = (List) runner.query(sql, new BeanListHandler(ManagerEntity.class));
			return list;
		}

		// 查询单个管理员,返回对象
		public ManagerEntity selectManager(String maccount) throws SQLException {
			QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
			String sql = "select * from manager where maccount=?";
			ManagerEntity Manager = (ManagerEntity) runner.query(sql, new BeanHandler(ManagerEntity.class), new Object[] { maccount });
			return Manager;
		}

		// 插入管理员
		public Boolean insertManager(ManagerEntity Manager) throws SQLException {
			QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
			String sql = "insert into manager (maccount,mpassword) values (?,?)";
			int num = runner.update(sql,
					new Object[] { Manager.getMaccount(), Manager.getMpassword() });
			if (num > 0)
				return true;
			return false;
		}
		
		// 删除管理员的操作
		public Boolean deleteManager(String maccount) throws SQLException {
			QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
			String sql = "delete from manager where maccount=?";
			int num = runner.update(sql, maccount);
			if (num > 0)
				return true;
			return false;
		}
		// 修改管理员的操作
		public Boolean updateManager(ManagerEntity Manager) throws SQLException {
			QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
			String sql = "update  manager set mpassword=? where maccount=?";
			int num = runner.update(sql, new Object[] { Manager.getMpassword(),
					Manager.getMaccount()  });
			if (num > 0)
				return true;
			return false;
		}
}

C3p0Utils:

package com.cqust.util;

import javax.sql.DataSource;
 
import com.mchange.v2.c3p0.ComboPooledDataSource;
 
public class C3p0Utils {
	
	private static ComboPooledDataSource cpds;
	static {
	cpds=new ComboPooledDataSource();
	 		// 设置连接数据库需要的配置信息
		try {
			cpds.setDriverClass("com.mysql.cj.jdbc.Driver");
			cpds.setJdbcUrl("jdbc:mysql://localhost:3306/database?serverTimezone=GMT%2B8");
			cpds.setUser("root");
			cpds.setPassword("11");
			cpds.setInitialPoolSize(5);
			cpds.setMaxPoolSize(15);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
public static DataSource getDataSource() {
	return cpds;
	}
}

就贴一个manager吧,其他的都一样了。

2.注册

注册页面
在这里插入图片描述
前端代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    
<link rel="stylesheet" href="layui/css/layui.css" media="all">
</head>

<body>
    <form class="login-form" action="RegisterServlet" id="form">
        <a href="log.html" class="login-a"><</a>
        <h1 style="font-size:30px;font-weight: bolder">注 册</h1>
         <div id="radios"> 
            <input type="radio" name="choice" value="1" checked="checked">管理员 <!--默认选中-->
            <input type="radio" name="choice" value="2">用户
            <input type="radio" name="choice" value="3">企业
        </div>
        <div class="tchoice">
            <div class="txtb">
                <input type="text" class="txtbinput" name="maccount">
                <span data-placeholder="账号"></span>
            </div>
            <div class="txtb">
                <input type="password" class="txtbinput" name="mpassword">
                <span data-placeholder="密码"></span>
            </div>
        </div>

        <div class="tchoice" style="display: none;">
            <div class="txtb">
                <input type="text" class="txtbinput" name="eaccount">
                <span data-placeholder="账号"></span>
            </div>
            <div class="txtb">
                <input type="password" class="txtbinput" name="epassword">
                <span data-placeholder="密码"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="ename">
                <span data-placeholder="用户名"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="eage">
                <span data-placeholder="年龄"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="ephone">
                <span data-placeholder="手机号"></span>
            </div>
        </div>

        <div class="tchoice" style="display: none;">
            <div class="txtb">
                <input type="text" class="txtbinput" name="caccount">
                <span data-placeholder="账号"></span>
            </div>
            <div class="txtb">
                <input type="password" class="txtbinput" name="cpassword">
                <span data-placeholder="密码"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="cname">
                <span data-placeholder="企业名"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="caddress">
                <span data-placeholder="地址"></span>
            </div>
            <div class="txtb">
                <input type="text" class="txtbinput" name="cmaster">
                <span data-placeholder="主管人"></span>
            </div>
        </div>
        <input type="submit" class="logbtn" value="注 册" id="sbtn">
    </form>
<script src="layui/layui.js"></script>
<script>
    layui.use([ 'form', 'jquery', 'table' ], function() {
		var form = layui.form;
		var $ = layui.jquery;
		
		$("#sbtn").click(function(){
			var url=$("#form").attr("action");
			var data=$("#form").serialize();
			console.log(data);
			$.ajax({
				url:url,
				type:'post',
				data:data,
				dataType:'json',
				success:function(re)
				{
					console.log("yes");
					layer.alert('注册成功!', {icon: 1,title:"提示"});
				},
				error: function(re)
				{
					console.log("no");
					layer.alert('注册失败!', {icon: 2,title:"提示"});
				}
			})
			return false; //阻止表单跳转
		})
		
    })
    
        var txt = document.getElementsByClassName("txtbinput");
        for (var i = 0; i <txt.length; i++) {
            txt[i].onfocus = function () {
                this.className = "focus";
            }
            txt[i].onblur = function () {
                if (this.value == "")
                    this.classList.remove("focus");
            }
        }
        var cho=document.getElementsByTagName("input");
        for(let i=0;i<=2;i++){
            cho[i].onclick=function(){
                var tcho=document.getElementsByClassName("tchoice");
                var tbody=document.getElementsByClassName("login-form")[0];
                for(var j=0;j<tcho.length;j++){
                    tcho[j].style.display="none";
                }
                tcho[i].style.display="block";
                if(i==0){
                    tbody.style.height="580px";
                    tbody.style.width="360px";
                }else if(i==1){
                    tbody.style.height="680px";
                    tbody.style.width="400px";
                }else{
                    tbody.style.height="680px";
                    tbody.style.width="400px";
                }
            }
        }
    </script>

</body>

</html>

后端
RegisterServlet:(其中ManagerBiz,ManagerEntity前面已经给出)

package com.cqust.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.cqust.biz.CompanyBiz;
import com.cqust.biz.EmployeeBiz;
import com.cqust.biz.ManagerBiz;
import com.cqust.dao.CompanyDao;
import com.cqust.dao.EmployeeDao;
import com.cqust.dao.ManagerDao;
import com.cqust.entity.CompanyEntity;
import com.cqust.entity.EmployeeEntity;
import com.cqust.entity.ManagerEntity;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		String choice = request.getParameter("choice");
		PrintWriter out = response.getWriter();
		if (choice.equals("1")) {// 管理员
			String maccount = request.getParameter("maccount");
			String mpassword = request.getParameter("mpassword");
			ManagerBiz biz = new ManagerBiz();
			ManagerEntity manager = biz.selectManager(maccount);
			if (manager == null) {
				ManagerEntity manager2 = new ManagerEntity(maccount, mpassword);
				boolean result = biz.insertManager(manager2);
				if (result == true) {
					String json = JSON.toJSONString(manager2);
					System.out.println(json);
					out.write(json);
				}
			}
		} else if (choice.equals("2")) {// 用户
			String eaccount = request.getParameter("eaccount");
			String epassword = request.getParameter("epassword");
			String ename = request.getParameter("ename");
			String eage = request.getParameter("eage");
			String ephone = request.getParameter("ephone");
			EmployeeBiz biz = new EmployeeBiz();
			EmployeeEntity employee = biz.selectEmployee(eaccount);
			if (employee == null) {
				EmployeeEntity employee2 = new EmployeeEntity(eaccount, epassword, ename, "", eage, ephone, "");
				boolean result = biz.insertEmployee(employee2);
				if (result == true) {
					String json = JSON.toJSONString(employee2);
					System.out.println(json);
					out.write(json);
				}
			}
		} else if (choice.equals("3")) {// 企业
			String caccount = request.getParameter("caccount");
			String cpassword = request.getParameter("cpassword");
			String cname = request.getParameter("cname");
			String caddress = request.getParameter("caddress");
			String cmaster = request.getParameter("cmaster");
			CompanyBiz biz = new CompanyBiz();
			CompanyEntity company = biz.selectCompany(caccount);
			if (company == null) {
				CompanyEntity company2 = new CompanyEntity(caccount, cpassword, cname, caddress, "", "", cmaster);
				boolean result = biz.insertCompany(company2);
				if (result == true) {
					String json = JSON.toJSONString(company2);
					System.out.println(json);
					out.write(json);
				}
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

3.数据库

在这里插入图片描述

在这里插入图片描述

202206192114日

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

baibai___

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值