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

这篇具有很好参考价值的文章主要介绍了Eclipse+servlet+Tomcat+MySQL实现登入注册页面。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

1.效果展示

2.环境搭建

3.前端代码

4.后端代码 

5.创作不易,点个赞吧


效果展示

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

 

登入界面

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

注册界面

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

注册一个账号Eclipse+servlet+Tomcat+MySQL实现登入注册页面

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

 

登入该账号

1.尝试输入错误密码

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

2.输入正确密码

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

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

再次注册该账号

 

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

环境搭建

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方法之上

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

后端代码 

先看一下我的文件结构

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

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 我推荐菜鸟教程,哈哈哈哈哈哈,我也是刚看的,文件名还没换呢

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

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

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

 Eclipse+servlet+Tomcat+MySQL实现登入注册页面文章来源地址https://www.toymoban.com/news/detail-425578.html

 创作不易,点个赞吧

到了这里,关于Eclipse+servlet+Tomcat+MySQL实现登入注册页面的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包