Eclipse+servlet+Tomcat+MySQL实现登入注册页面

目录

1.效果展示

2.环境搭建

3.前端代码

4.后端代码 

5.创作不易,点个赞吧


效果展示

 

登入界面

注册界面

注册一个账号

 

登入该账号

1.尝试输入错误密码

2.输入正确密码

再次注册该账号

 

环境搭建

MySQL下载安装网上都有可以参考http://t.csdn.cn/czWMN

Eclipse搭载MySQLhttp://t.csdn.cn/NKXAh

这边说一点 javaWeb项目中无法驱动数据库 http://t.csdn.cn/jwKcA

tomcat下载安装 http://t.csdn.cn/EKMxB

Eclipse搭载tomcat http://t.csdn.cn/bCd6q

搭配过程中可能出现的问题:

1.设置里面没有Server  http://t.csdn.cn/LZCeq

2.以上办法出现无法安装 http://t.csdn.cn/nVlL9

其他的网上都有

前端代码

1.hello.html

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      background: url('https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547_1280.jpg') no-repeat;
      background-size: 100% 130%;
    }

    #login_box {
      width: 20%;
      height: 400px;
      background-color: #262d2a60;
      margin: auto;
      margin-top: 10%;
      text-align: center;
      border-radius: 10px;
      padding: 50px 50px;
    }

    h2 {
      color: #ffffff90;
      margin-top: 5%;
    }

    #input-box {
      margin-top: 5%;
    }

    span {
      color: #fff;
    }

    input {
      border: 0;
      width: 60%;
      font-size: 15px;
      color: #fff;
      background: transparent;
      border-bottom: 2px solid #fff;
      padding: 5px 10px;
      outline: none;
      margin-top: 10px;
    }

    #submitbtn {
      margin-top: 50px;
      width: 60%;
      height: 40px;
      border-radius: 10px;
      border: 0;
      color: #fff;
      text-align: center;
      line-height: 30px;
      font-size: 15px;
      background-image: linear-gradient(to right, #30cfd0, #330867);
    }
 

    a {
      color: #2f6d84;
      text-decoration: none;
    }
    
    #bottom{
      margin-top: 50px; 
    }
    #signup{
      margin-left: 100px;
    }

    #loginFail{
      color: rgb(215, 40, 40);
    }
  </style> 
  <script>
    function check(){
      var no=document.getElementById("no").value;
      var pw=document.getElementById("pw").value;
      var legal=true;
      if(no.length<8||no.length>20)legal=false;
      else if(pw.length<8||pw.length>20)legal=false;
      if(!legal)document.getElementById("loginFail").innerHTML="账号或者密码错误"; 

      return legal;
    }
    function deleteFailtext(){
      document.getElementById("loginFail").innerHTML="";
    }
  </script>
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <script>
    	// form 表单提交数据的话 会自动跳转 我并不希望他这么做
       //用ajax
    function testAjax(){
    	//简单的判断
      if(!check())return;
      $.ajax({
                   url: "HelloForm",    //请求的url地址
                   dataType: "json",   //返回格式为json
                   async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                   data: {
                   			 "username": document.getElementById("no").value,
                         "password": document.getElementById("pw").value
                   		 },    //参数值
                  type: "GET",  
                  success: function(req) {
                      var login=req[0].login;
                      //登入成功
                      if(login=="true"){ 
                    	  window.location.href="MainPage.html";
                      }
                      else {
                        $("#loginFail").html("账号或者密码错误");
                      }
                  },
                  error: function() {
                      //请求出错处理
                      //可能是返回的json格式出错
                      alert("error");
                  }
        });
    }
    </script>
</head> 
<body>
  <div id="login_box">
    <h2>LOGIN</h2> 
      <form action="HelloForm" method="post" target="myIframe">
      	<span id="loginFail"></span>
        <div id="input_box">
          <input type="text" id="no" name="username" placeholder="请输入用户名" onclick="deleteFailtext()">
        </div>
        <div class="input_box">
          <input type="password" id="pw" name="password" placeholder="请输入密码" onclick="deleteFailtext()">
        </div>
        <input type="button" id="submitbtn" value="登入" onclick="testAjax()">
      </form> 
      <div id="bottom">
        <a href="misspassword.html" id="misspassword">忘记密码?</a>
        <a href="signup.html" id="signup">注册</a>
      </div>
  </div>
</body>
</html>

2.signup.html

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body {
      background: url('http://pic1.win4000.com/wallpaper/4/591564dfe432a.jpg') no-repeat;
      background-size: 100% 130%;
    }

    #login_box {
      width: 20%;
      height: 400px;
      background-color: #262d2a60;
      margin: auto;
      margin-top: 10%;
      text-align: center;
      border-radius: 10px;
      padding: 50px 50px;
    }

    h2 {
      color: #ffffff90;
      margin-top: 5%;
    }

    #input-box {
      margin-top: 5%;
    }

    span {
      color: #fff;
    }

    input {
      border: 0;
      width: 60%;
      font-size: 15px;
      color: #fff;
      background: transparent;
      border-bottom: 2px solid #fff;
      padding: 5px 10px;
      outline: none;
      margin-top: 10px;
    }

    #submitbtn {
      margin-top: 50px;
      width: 60%;
      height: 40px;
      border-radius: 10px;
      border: 0;
      color: #fff;
      text-align: center;
      line-height: 30px;
      font-size: 15px;
      background-image: linear-gradient(to right, #30cfd0, #330867);
    }
 

    a {
      color: #2f6d84;
      text-decoration: none;
    }
       
  </style> 
  <script>
    function nocheck(){
      var legal=true;
        var ps=document.getElementById("no").value;
        if(ps.length==0){
            document.getElementById("noinfor").innerHTML="";
            legal=false;
            return;
        }
        if(ps.length!=11){
          legal=false;
            document.getElementById("noinfor").innerHTML="×";
        }
        else document.getElementById("noinfor").innerHTML="√";
        return legal;
    }
    function firstpwcheck(){
      var legal=true;
        var ps=document.getElementById("pw").value;
        if(ps.length==0){
            document.getElementById("firpwinfor").innerHTML="";
            legal=false;
            return;
        }
        if(ps.length<8||ps.length>20){ 
            document.getElementById("firpwinfor").innerHTML="×";
            legal=false;
        }
        else {
            document.getElementById("firpwinfor").innerHTML="√"; 
        }
        return legal;
    }
    function secpwcheck(){
      var legal=true;
        var psa=document.getElementById("pwa").value;
        var ps=document.getElementById("pw").value;
        if(psa.length==0){
            document.getElementById("secpwinfor").innerHTML="";
            legal=false;
            return;
        }
        if(ps!=psa){
            document.getElementById("secpwinfor").innerHTML="×";
            legal=false;
            return;
        }
        document.getElementById("secpwinfor").innerHTML="√";
        return legal;
    }
    function usernamecheck(){
      var legal=true;
        var ps=document.getElementById("username").value;
        if(ps.length==0){
            document.getElementById("usernameinfor").innerHTML="";
            legal=false;
            return;
        } 
         document.getElementById("usernameinfor").innerHTML="√";
         return legal;
    }
  </script>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <script>
    // form 表单提交数据的话 会自动跳转 我并不希望他这么做
     //用ajax
  function testAjax(){ 
    //简单的判断
    if(!nocheck()||!usernamecheck()||!firstpwcheck()||!secpwcheck()){
    	alert("请完善所有信息");
    	return;
    }
    $.ajax({
                 url: "register",    //请求的url地址
                 dataType: "json",   //返回格式为json
                 async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                 data: {
                        "no": document.getElementById("no").value,
                       "password": document.getElementById("pw").value,
                       "username": document.getElementById("username").value
                      },    //参数值
                type: "GET",  
                success: function(req) {
                    var signup=req[0].flag;
                    //登入成功跳转到登入界面
                    if(signup=="true"){ 
                    	alert("注册成功!请返回登入");
                      window.location.href="hello.html";
                    } 
                    else {
                    	alert("注册失败!用户名已存在");
                    }
                },
                error: function() {
                    //请求出错处理
                    //可能是返回的json格式出错
                    alert("error");
                }
      });
  }
  </script>
</head> 
<body>
  <div id="login_box">
    <h2>SIGN UP</h2> 
      <form action="HelloForm" method="post"> 
        <div id="input_box">
          <input type="text" id="no" name="no" placeholder="请输入用户名(手机号或者邮箱)" onkeyup="nocheck()">
          <span id="noinfor"></span>
        </div>
        <div id="input_box">
            <input type="text" id="username" name="username" placeholder="请输入昵称" onkeyup="usernamecheck()">
            <span id="usernameinfor"></span>
          </div>
        <div class="input_box">
          <input type="password" id="pw" name="password" placeholder="请输入密码" onkeyup="firstpwcheck()">
          <span id="firpwinfor"></span>
        </div>
        <div class="input_box">
            <input type="password" id="pwa" name="passworda" placeholder="请再次输入密码" onkeyup="secpwcheck()">
            <span id="secpwinfor"></span>
        </div>
        <input type="button" id="submitbtn" value="注册" onclick="testAjax()">
      </form> 
      <div id="bottom"> 

      </div>
  </div>
</body>
</html>

内容我就不解释了html没怎么学,说一下前后端数据交互问题吧

form表单交互 

<form action="后端接受方地址" method="方式POST或者GET" target="myIframe">
      	<span id="loginFail"></span>
        <div id="input_box">
          <input type="text" id="no" name="username" placeholder="请输入用户名" onclick="deleteFailtext()">
        </div>
        <div class="input_box">
          <input type="password" id="pw" name="password" placeholder="请输入密码" onclick="deleteFailtext()">
        </div>
        <input type="submit" id="submitbtn" value="登入">
      </form> 

按钮type得是submit,会跳转

ajax交互

function testAjax(){ 
      $.ajax({
                   url: "HelloForm",    //请求的url地址
                   dataType: "json",   //返回格式为json
                   async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                   data: {
                            //数据
                   		 "username": document.getElementById("no").value,
                         "password": document.getElementById("pw").value
                   		 },    //参数值
                  type: "GET",  //方式
                      //成功处理,我想这边的成功应该是接受到反馈的信息就算成功吧
                  success: function(req) {
                      var login=req[0].login;
                      //登入成功
                      if(login=="true"){ 
                    	  window.location.href="MainPage.html";
                      }
                      else {
                        $("#loginFail").html("账号或者密码错误");
                      }
                  },
                  error: function() {
                      //请求出错处理
                      //可能是返回的json格式出错
                      alert("error");
                  }
        });
    }

这时候按钮不需要submit就可以传输信息,登入界面我更喜欢用这个

注意需要引入包

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

而且在代码中最好放在 ajax方法之上

其他的不多说了.....

后端代码 

先看一下我的文件结构

User.java

package user;

public class User {
	//用户ID
	int user_id;
	//用户昵称
	String user_name;  
	//账号密码
	String no;
	String password;
	//区分是否为管理员
	//所有页面注册的都是普通用户 管理员由后端指定 以0为普通用户 1为管理员
	int role_id=0;
	public User() {
		this.no="";
		this.password="";
	}
	public User(String no,String password) {
		this.no=no;
		this.password=password;
	}
	public User(String no,String password,String user_name) {
		this.no=no;
		this.password=password;
		this.user_name=user_name;
	}
	public void setUsername(String a) {
		this.no=a;
	}
	public void setPassword(String a) {
		this.password=a;
	}
	public void setUser_id(int id) {
		this.user_id=id;
	}
}

UserDao.java

package user;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import database.Connect;
 

public class UserDao {
	User user;
	Connect connect=new Connect();
	Connection connection=null;
	public void setUser(User u) {
		this.user=u;
	}
	//连接数据库
	public void getConnection() {
		connection=connect.getConnection();
	}
	//释放数据库
	public void deleteConnection() throws SQLException {
		if(connection!=null) {
			connection.close();
		} 
		connection=null;
	}
	//用户登入是否成功
	public boolean checkUserLogin() {
		if(user==null)return false; 
		try {
			PreparedStatement presta=connection.prepareStatement("select *"
					+ " from user where no like ? and password like ? ;");
			//同时验证账号密码
			presta.setString(1, user.no);
			presta.setString(2, user.password);
			boolean a=presta.executeQuery().next();
			presta.close();
			return a;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	//用户是否存在 用于注册页面判断
	public boolean checkUserExist() {
		if(user==null)return false;  
		try {
			Statement statement=connection.createStatement();
			//只需验证用户名是否存在
			String sql="select * from user where no = "+user.no+";";
			boolean a=statement.executeQuery(sql).next();
			statement.close();
			return a;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	//注册成功 应该在前端判断成功之后才调用此函数
	public void addUser() {
		//查找最大的用户ID 然后 此用户ID+1 特别注意线程安全(将来完善)
		int MaxUserId=-1; 
		try {
			Statement statement=connection.createStatement();
			//
			String sql="select max(user_id) id from user";
			//是否是第一个用户  如果不是ID=MAXID+1 
			ResultSet rs=statement.executeQuery(sql);
			MaxUserId=rs.next()?rs.getInt("id")+1:0;
			//
			this.user.setUser_id(MaxUserId);
			String updateSql="insert into user values(?,?,?,?,?);";
			PreparedStatement presta=connection.prepareStatement(updateSql);
			presta.setInt(1, MaxUserId);
			presta.setString(2, user.no);
			presta.setString(3, user.user_name);
			presta.setString(4, user.password);
			presta.setInt(5, user.role_id);
			presta.executeUpdate();
			statement.close();
			presta.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 Connect.java

package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; 

public class Connect {
	Connection con;
	public static String user;
	public static String password;
    public Connection getConnection() {
        try { // 加载数据库驱动类
            //记得在lib下面放jar包
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("数据库驱动加载成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        user = "root";//数据库登录名
        password = "你自己的密码";//密码
        try { // 通过访问数据库的URL获取数据库连接对象
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/你自己的数据库?useUnicode=true&characterEncoding=utf-8",
            		user, password);
            System.out.println("数据库连接成功");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con; // 按方法要求返回一个Connection对象
	}  
}

 HelloForm.java

package com.servlets;

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 user.User;
import user.UserDao;

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

	UserDao user=new UserDao();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloForm() {
        super(); 
        System.out.println("HelloForm occur");
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
		request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        String login="false";
        System.out.println(name+" "+password);
        //验证  
        user.getConnection();
        user.setUser(new User(name,password));
        login=Boolean.toString(user.checkUserLogin());
        try {
			user.deleteConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //Json格式不能出错
        String buffer = "[{\"login\":"+"\""+login+"\"}]";  
        System.out.println(buffer);
		//写入回复中
        PrintWriter writer = response.getWriter();
        writer.write(buffer);
        writer.close(); 
    }
    
    // 处理 POST 方法请求的方法
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

register.java

package com.servlets;

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 user.User;
import user.UserDao;

/**
 * Servlet implementation class register
 */
@WebServlet("/register")
public class register extends HttpServlet {
	UserDao user=new UserDao();
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public register() {
        super();
        System.out.println("register occur");
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 // 设置响应内容类型
		request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String no=request.getParameter("no");
        String password=request.getParameter("password");
        String username=request.getParameter("username");  
        System.out.println(no+" "+password+" "+username);
        user.getConnection();
        user.setUser(new User(no,password,username));
        boolean usernoexist=user.checkUserExist();
        //用户不存在 添加到数据库
        if(!usernoexist) {
        	user.addUser();
        }
        try {
			user.deleteConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //Json格式不能出错
        String buffer = "[{\"flag\":"+"\""+!usernoexist+"\"}]"; 
        System.out.println(buffer);
		//写入回复中
        PrintWriter writer = response.getWriter();
        writer.write(buffer);
        writer.close(); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

至此,就完成了简单的登入注册

关于使用servlet 我推荐菜鸟教程,哈哈哈哈哈哈,我也是刚看的,文件名还没换呢

 

 

 

 创作不易,点个赞吧

以下是一个简单的登入注册页面的 HTML 代码示例: ``` <!DOCTYPE html> <html> <head> <title>Login/Registration page</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body { margin: 0; padding: 0; background-color: #f2f2f2; font-family: Arial, sans-serif; } form { background-color: #fff; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); padding: 20px; margin: 20px auto; max-width: 400px; } h1 { text-align: center; margin-top: 0; } input[type=text], input[type=password] { display: block; margin: 10px 0; padding: 10px; border-radius: 5px; border: none; width: 100%; box-sizing: border-box; font-size: 16px; } input[type=submit] { background-color: #4CAF50; color: #fff; border: none; border-radius: 5px; padding: 10px; width: 100%; cursor: pointer; font-size: 16px; } input[type=submit]:hover { background-color: #3e8e41; } .error { color: red; margin-bottom: 10px; } .success { color: green; margin-bottom: 10px; } .switch { text-align: center; margin-bottom: 10px; } .switch a { color: #4CAF50; text-decoration: none; font-size: 14px; } </style> </head> <body> <form action="login.php" method="post" id="login-form"> <h1>Login</h1> <div class="error"></div> <div class="success"></div> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <input type="submit" value="Login"> <div class="switch">New user? <a href="#" id="register-link">Register here</a></div> </form> <form action="register.php" method="post" id="register-form" style="display: none;"> <h1>Register</h1> <div class="error"></div> <div class="success"></div> <label for="new-username">Username:</label> <input type="text" id="new-username" name="new-username" required> <label for="new-password">Password:</label> <input type="password" id="new-password" name="new-password" required> <input type="submit" value="Register"> <div class="switch">Already a user? <a href="#" id="login-link">Login here</a></div> </form> <script> // Switch between login and register forms const loginForm = document.getElementById("login-form"); const registerForm = document.getElementById("register-form"); const loginLink = document.getElementById("login-link"); const registerLink = document.getElementById("register-link"); loginLink.addEventListener("click", function(event) { event.preventDefault(); loginForm.style.display = "block"; registerForm.style.display = "none"; }); registerLink.addEventListener("click", function(event) { event.preventDefault(); loginForm.style.display = "none"; registerForm.style.display = "block"; }); </script> </body> </html> ``` 这个页面包括了一个登入表单和一个注册表单,用户可以通过点击链接在两个表单之间切换。您需要将表单的 action 属性设置为实际的登入和注册处理文件的 URL。注意,这只是一个示例,您需要根据自己的需求进行修改。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值