实现登录与注册
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";}elseif(data1.result=="employee"){window.location.href="index.html?myaccount="+$("#ac").val()+"&type=e";}elseif(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;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.SQLException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.cqust.biz.CompanyBiz;importcom.cqust.biz.EmployeeBiz;importcom.cqust.biz.ManagerBiz;importcom.cqust.entity.CompanyEntity;importcom.cqust.entity.EmployeeEntity;importcom.cqust.entity.ManagerEntity;
@WebServlet("/LoginServlet")publicclassLoginServlet extends HttpServlet {privatestaticfinallong serialVersionUID =1L;protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/pages/addUser.jsp");
rd.forward(request, response);}protectedvoiddoPost(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 =newManagerBiz();
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'}";}}}elseif(choice.equals("2")){
EmployeeBiz eBiz =newEmployeeBiz();
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'}";}}}elseif(choice.equals("3")){
CompanyBiz cBiz =newCompanyBiz();
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;publicclassManagerEntity{private String maccount;private String mpassword;public String getMaccount(){return maccount;}publicvoidsetMaccount(String maccount){this.maccount = maccount;}public String getMpassword(){return mpassword;}publicvoidsetMpassword(String mpassword){this.mpassword = mpassword;}publicManagerEntity(String maccount, String mpassword){super();this.maccount = maccount;this.mpassword = mpassword;}publicManagerEntity(){super();// TODO Auto-generated constructor stub}}
ManagerBiz代码:
package com.cqust.biz;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importorg.apache.commons.dbutils.handlers.BeanListHandler;importcom.cqust.dao.ManagerDao;importcom.cqust.entity.EmployeeEntity;importcom.cqust.entity.ManagerEntity;publicclassManagerBiz{privatestatic ManagerDao dao =newManagerDao();public ManagerEntity selectManager(String account){//查询单个
ManagerEntity manager=newManagerEntity();try{
manager=dao.selectManager(account);}catch(SQLException e){
e.printStackTrace();}return manager;}public List selectAllManagers(){//查询所有
List<ManagerEntity> list =newArrayList<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;importjava.sql.SQLException;importjava.util.List;importorg.apache.commons.dbutils.QueryRunner;importorg.apache.commons.dbutils.handlers.BeanHandler;importorg.apache.commons.dbutils.handlers.BeanListHandler;importcom.cqust.entity.ManagerEntity;importcom.cqust.util.C3p0Utils;publicclassManagerDao{// 查询所有管理员,返回List集合public List selectAllManagers() throws SQLException {
QueryRunner runner =newQueryRunner(C3p0Utils.getDataSource());
String sql ="select * from manager";
List list =(List) runner.query(sql,newBeanListHandler(ManagerEntity.class));return list;}// 查询单个管理员,返回对象public ManagerEntity selectManager(String maccount) throws SQLException {
QueryRunner runner =newQueryRunner(C3p0Utils.getDataSource());
String sql ="select * from manager where maccount=?";
ManagerEntity Manager =(ManagerEntity) runner.query(sql,newBeanHandler(ManagerEntity.class),new Object[]{ maccount });return Manager;}// 插入管理员public Boolean insertManager(ManagerEntity Manager) throws SQLException {
QueryRunner runner =newQueryRunner(C3p0Utils.getDataSource());
String sql ="insert into manager (maccount,mpassword) values (?,?)";int num = runner.update(sql,new Object[]{ Manager.getMaccount(), Manager.getMpassword()});if(num >0)returntrue;returnfalse;}// 删除管理员的操作public Boolean deleteManager(String maccount) throws SQLException {
QueryRunner runner =newQueryRunner(C3p0Utils.getDataSource());
String sql ="delete from manager where maccount=?";int num = runner.update(sql, maccount);if(num >0)returntrue;returnfalse;}// 修改管理员的操作public Boolean updateManager(ManagerEntity Manager) throws SQLException {
QueryRunner runner =newQueryRunner(C3p0Utils.getDataSource());
String sql ="update manager set mpassword=? where maccount=?";int num = runner.update(sql,new Object[]{ Manager.getMpassword(),
Manager.getMaccount()});if(num >0)returntrue;returnfalse;}}
C3p0Utils:
package com.cqust.util;importjavax.sql.DataSource;importcom.mchange.v2.c3p0.ComboPooledDataSource;publicclassC3p0Utils{privatestatic ComboPooledDataSource cpds;static{
cpds=newComboPooledDataSource();// 设置连接数据库需要的配置信息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){thrownewExceptionInInitializerError(e);}}publicstatic 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:"提示"});}})returnfalse;//阻止表单跳转})})
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";}elseif(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;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.alibaba.fastjson.JSON;importcom.cqust.biz.CompanyBiz;importcom.cqust.biz.EmployeeBiz;importcom.cqust.biz.ManagerBiz;importcom.cqust.dao.CompanyDao;importcom.cqust.dao.EmployeeDao;importcom.cqust.dao.ManagerDao;importcom.cqust.entity.CompanyEntity;importcom.cqust.entity.EmployeeEntity;importcom.cqust.entity.ManagerEntity;
@WebServlet("/RegisterServlet")publicclassRegisterServlet extends HttpServlet {privatestaticfinallong serialVersionUID =1L;protectedvoiddoGet(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 =newManagerBiz();
ManagerEntity manager = biz.selectManager(maccount);if(manager == null){
ManagerEntity manager2 =newManagerEntity(maccount, mpassword);
boolean result = biz.insertManager(manager2);if(result ==true){
String json = JSON.toJSONString(manager2);
System.out.println(json);
out.write(json);}}}elseif(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 =newEmployeeBiz();
EmployeeEntity employee = biz.selectEmployee(eaccount);if(employee == null){
EmployeeEntity employee2 =newEmployeeEntity(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);}}}elseif(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 =newCompanyBiz();
CompanyEntity company = biz.selectCompany(caccount);if(company == null){
CompanyEntity company2 =newCompanyEntity(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);}}}}protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {doGet(request, response);}}
3.数据库
202206192114日
版权归原作者 白— 所有, 如有侵权,请联系我们删除。