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

实现登录与注册

需要引入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日

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
### 回答1: Springboot Vue 前后端分离登录注册代码可以通过使用RESTful API来实现,它可以帮助前端和后端之间的数据传输。后端可以使用Spring Boot框架来构建RESTful API,而前端则可以使用Vue.js来调用后端API实现登录或注册。 ### 回答2: Spring Boot和Vue.js是非常流行的前后端分离框架,可以很方便地进行登录注册功能的开发。 在后端Spring Boot中,首先需要创建一个UserController类来处理用户相关的请求,包括注册和登录。在UserController中,我们可以定义两个POST请求的接口,一个用于用户注册,一个用于用户登录。 用户注册接口可以接收一个User对象作为参数,User对象包含了用户的用户名和密码等信息。在用户注册接口中,我们可以先检查数据库中是否存在相同用户名的用户,如果不存在,则可以将用户信息保存到数据库中,并返回相应的注册成功提示。 用户登录接口可以接收一个LoginRequest对象作为参数,LoginRequest对象包含了用户输入的用户名和密码。在用户登录接口中,我们可以通过用户名在数据库中查询对应的用户信息,然后比对密码是否正确,如果正确则返回登录成功的提示,否则返回登录失败的提示。 在前端Vue.js中,我们可以使用axios来发送HTTP请求,调用后端提供的接口。在注册页面,可以通过表单获取用户输入的用户名和密码,并发送POST请求到后端的注册接口。在登录页面,也是通过表单获取用户输入的用户名和密码,并发送POST请求到后端的登录接口。 后端返回的响应可以根据具体需求进行处理,比如注册成功后可以跳转到登录页面,登录成功后可以跳转到主页。 总结起来,通过Spring Boot提供的后端接口和Vue.js提供的前端页面,前后端分离登录注册功能可以很方便地实现。以上是一个简单的示例,实际的实现会根据具体需求和业务逻辑而有所不同。 ### 回答3: springboot是一个应用程序框架,而vue是一个用于构建用户界面的前端框架。在前后端分离的架构中,前后端分别使用不同的技术进行开发,并通过接口进行通信。下面是一个简单示例的登录注册代码: 后端(使用springboot): 1. 创建一个UserController类,用于处理与用户相关的请求。 2. 在该类中,创建登录和注册的接口,分别对应/login和/register路径。 3. 在登录接口中,获取前端传来的用户名和密码,并与数据库中的用户信息进行比较。若比对成功,则返回成功信息;否则返回失败信息。 4. 在注册接口中,获取前端传来的用户名和密码,并将用户信息存入数据库。 5. 使用spring security等权限管理框架,对接口进行安全验证,确保只有经过认证的用户才能访问。 前端(使用vue): 1. 创建一个Login.vue和Register.vue组件,分别用于登录和注册界面的展示。 2. 在组件中,创建表单,用于用户输入用户名和密码。 3. 在提交按钮点击事件中,使用axios等,将用户输入的信息发送给后端的登录或注册接口。 4. 根据接口返回的结果,在前端展示登录或注册成功或失败的信息。 总结: 以上代码只是一个简单示例,实际开发中可能涉及更多功能的实现。通过springboot和vue的前后端分离架构,可以实现页面与后端数据的分离,提升开发效率和灵活性。为了保证系统安全性,还需要加入权限管理等措施。这里只提供了一个基本的框架,具体的实现和功能可以根据需求进行扩展和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

baibai___

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

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

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

打赏作者

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

抵扣说明:

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

余额充值