Java 实现用户注册登陆

一个用户注册登陆的系统,用到了MD5加密处理密码,实现了一个简单的数据库连接池connectionPool,

实现了注册,登陆,登陆之后修改用户信息等功能,非常适合初学者

一.准备工作

数据库:MySQL  5.5.62-log MySQL Community Server (GPL)

创建user表,数据库为first_db;

CREATE TABLE IF NOT EXISTS `user`(
`user_id` INT UNSIGNED AUTO_INCREMENT,
 `username` VARCHAR(100) NOT NULL,
 `password` VARCHAR(100) NOT NULL,
 `phone` VARCHAR(100) NOT NULL, PRIMARY KEY ( `user_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

二.项目结构图:

 

三.部分核心代码

web.xml:  

实现servlet指向CheckUser类和UpdateUser类,指定login.jsp为首页

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <servlet>
    <servlet-name>CheckUser</servlet-name>
    <servlet-class>com.Account.CheckUser</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>UpdateUser</servlet-name>
    <servlet-class>com.Account.UpdateUser</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CheckUser</servlet-name>
    <url-pattern>/CheckUser</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UpdateUser</servlet-name>
    <url-pattern>/UpdateUser</url-pattern>
  </servlet-mapping> 
  
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

login.jsp:

login.jsp是登陆页面,from表单中加了一个<input type="hidden" name="actiontype" value="login" />的隐藏按钮,用于在CheckUser类中判断是登陆还是注册,通过actiontype的值。点击登陆,根据servlet分发到CheckUser类处理请求

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
  <head>
    <title>登陆</title>
  </head>
  <body>
        <h2>欢迎登陆</h2>
    	<form action="CheckUser" method="post">
    		账号:<input type="text" name="userName"><br/>
    		密码:<input type="password" name="password"><br/>
    		<input type="hidden" name="actiontype" value="login" /> <!-- 用隐藏域来判断登陆还是注册 -->
    		<input type="submit" value="登陆"/><br/><br />
    	</form>
  	    <button onclick="window.location='register.jsp'">注册</button>
    	${sessionScope.errorMsg} <!-- EL语法--获取session的errorMsg并显示 -->
  </body>
</html>

 

CheckUser.java:

实现处理登陆注册的请求 向数据库请求并返回结果

package com.Account;
import java.io.IOException;

import java.sql.Connection;
//import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class CheckUser extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		//md5对密码加密
		Md5 md5=new Md5();
		
		//判断类型是登陆还是注册
		String Sql="";
		String action_type = request.getParameter("actiontype");
		if(action_type.equals("login")){
			 Sql = "SELECT user_id,username,password,phone FROM user "
			 		+ "where username='" + userName+ "' AND password='" + md5.MD5(password) + "' ";
		}else if(action_type.equals("register")){
			 Sql = "INSERT into user (username,password,phone) values ('"+ userName+"' ,'"+md5.MD5(password) +"',' ')";
		}
		
		Connection connection = null;
		PreparedStatement preSta = null;
		ResultSet rs = null;
		
		// 建立连接,DriverManager是JDBC的管理层
		try {
			//使用连接池的方式连接数据库
			ConnectionPool.setUrl(ConnectionPool.getUrl());
			ConnectionPool.setUser(ConnectionPool.getUser());//DBTools.getDatabaseUserName()
			ConnectionPool.setPassword(ConnectionPool.getPassword());

			connection = ConnectionPool.getConnection();
			preSta = connection.prepareStatement(Sql);
			
			UserInfo info = null;
		
			if(action_type.equals("login")) {
				rs = preSta.executeQuery();
				while(rs.next()){
					info = new UserInfo();
					info.setuser_id(rs.getInt("user_id"));
					info.setUserName(rs.getString("username"));
					info.setPassword(rs.getString("password"));
					info.setPhone(rs.getString("phone"));
				}
				if(info != null){
					session.setAttribute("password", password);
					session.setAttribute("info", info);
					String login_suc = "success.jsp";
					response.sendRedirect(login_suc);
				}
				else{
					String login_fail = "login.jsp";
					session.setAttribute("errorMsg", "用户名或密码错误,登陆失败!");
					response.sendRedirect(login_fail); 
				}
			}
			else if(action_type.equals("register")){
 			   int count= preSta.executeUpdate();
 			   if(count>0){
					session.setAttribute("registerMsg", "注册成功!");
				}
				else{
					session.setAttribute("registerMsg", "注册失败,请重试!");
				}
 				response.sendRedirect("register.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 关闭连接
		finally {
			if(connection!=null){
				try{
					connection.close();
				}catch(Exception e){}
			}
			if(preSta!=null){
				try{
					preSta.close();
				}catch(Exception e){}
			}
			if(rs!=null){
				try{
					rs.close();
				}catch(Exception e){}
			}
		}
	}
}

 

MD5.Java:

MD5加密类,给password字段加密

package com.Account;

import java.security.MessageDigest;

public class Md5 {
	public final String MD5(String s) {//MD5加密方法
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; //>>>不带符号 右移 四位(位移处补0)
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
	}
}

 

ConnectionPool.java:

手动实现一个简单的数据库连接池,提升性能

package com.Account;

import java.sql.*;
import java.lang.reflect.*;
import java.util.*;
import java.io.*;

public class ConnectionPool {
	private static LinkedList m_notUsedConnection = new LinkedList();
	private static HashSet m_usedUsedConnection = new HashSet();
	private static String m_url = "jdbc:mysql://localhost:3306/first_db";
	private static String m_user = "root";
	private static String m_password = "123456";
	static final boolean DEBUG = true;
	static private long m_lastClearClosedConnection = System.currentTimeMillis();
	public static long CHECK_CLOSED_CONNECTION_TIME = 4 * 60 * 60 * 1000; // 4小时
	
	private void ConnectionPool() {
	}
	
	static {
		initDriver();
	}

	private static void initDriver() {
		Driver driver = null;
		// load mysql driver
		try {
			driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
			installDriver(driver);
		} catch (Exception e) {
		}
	}

	public static void installDriver(Driver driver) {
		try 
		{
			DriverManager.registerDriver(driver);
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static synchronized Connection getConnection() {
		clearClosedConnection();
		while (m_notUsedConnection.size() > 0) {
			try {
				ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection
						.removeFirst();
				if (wrapper.connection.isClosed()) {
					continue;
				}
				m_usedUsedConnection.add(wrapper);
				if (DEBUG) {
					wrapper.debugInfo = new Throwable(
							"Connection initial statement");
				}
				return wrapper.connection;
			} catch (Exception e) {
			}
		}
		int newCount = getIncreasingConnectionCount();
		LinkedList list = new LinkedList();
		ConnectionWrapper wrapper = null;
		for (int i = 0; i < newCount; i++) {
			wrapper = getNewConnection();
			if (wrapper != null) {
				list.add(wrapper);
			}
		}
		if (list.size() == 0) {
			return null;
		}
		wrapper = (ConnectionWrapper) list.removeFirst();
		m_usedUsedConnection.add(wrapper);

		m_notUsedConnection.addAll(list);
		list.clear();

		return wrapper.connection;
	}

	private static ConnectionWrapper getNewConnection() {
		try {
			Connection con = DriverManager.getConnection(m_url, m_user,
					m_password);
			ConnectionWrapper wrapper = new ConnectionWrapper(con);
			return wrapper;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	static synchronized void pushConnectionBackToPool(ConnectionWrapper con) {
		boolean exist = m_usedUsedConnection.remove(con);
		if (exist) {
			m_notUsedConnection.addLast(con);
		}
	}

	public static int close() {
		int count = 0;

		Iterator iterator = m_notUsedConnection.iterator();
		while (iterator.hasNext()) {
			try {
				((ConnectionWrapper) iterator.next()).close();
				count++;
			} catch (Exception e) {
			}
		}
		m_notUsedConnection.clear();

		iterator = m_usedUsedConnection.iterator();
		while (iterator.hasNext()) {
			try {
				ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
				wrapper.close();
				if (DEBUG) {
					wrapper.debugInfo.printStackTrace();
				}
				count++;
			} catch (Exception e) {
			}
		}
		m_usedUsedConnection.clear();

		return count;
	}

	private static void clearClosedConnection() {
		long time = System.currentTimeMillis();
		// sometimes user change system time,just return
		if (time < m_lastClearClosedConnection) {
			time = m_lastClearClosedConnection;
			return;
		}
		// no need check very often
		if (time - m_lastClearClosedConnection < CHECK_CLOSED_CONNECTION_TIME) {
			return;
		}
		m_lastClearClosedConnection = time;

		// begin check
		Iterator iterator = m_notUsedConnection.iterator();
		while (iterator.hasNext()) {
			ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
			try {
				if (wrapper.connection.isClosed()) {
					iterator.remove();
				}
			} catch (Exception e) {
				iterator.remove();
				if (DEBUG) {
					System.out
							.println("connection is closed, this connection initial StackTrace");
					wrapper.debugInfo.printStackTrace();
				}
			}
		}

		// make connection pool size smaller if too big
		int decrease = getDecreasingConnectionCount();
		if (m_notUsedConnection.size() < decrease) {
			return;
		}

		while (decrease-- > 0) {
			ConnectionWrapper wrapper = (ConnectionWrapper) m_notUsedConnection
					.removeFirst();
			try {
				wrapper.connection.close();
			} catch (Exception e) {
			}
		}
	}

	/**
	 * get increasing connection count, not just add 1 connection
	 * 
	 * @return count
	 */
	public static int getIncreasingConnectionCount() {
		int count = 1;
		int current = getConnectionCount();
		count = current / 4;
		if (count < 1) {
			count = 1;
		}
		return count;
	}

	/**
	 * get decreasing connection count, not just remove 1 connection
	 * 
	 * @return count
	 */
	public static int getDecreasingConnectionCount() {
		int count = 0;
		int current = getConnectionCount();
		if (current < 10) {
			return 0;
		}
		return current / 3;
	}

	public synchronized static void printDebugMsg() {
		printDebugMsg(System.out);
	}

	public synchronized static void printDebugMsg(PrintStream out) {
		if (DEBUG == false) {
			return;
		}
		StringBuffer msg = new StringBuffer();
		msg.append("debug message in " + ConnectionPool.class.getName());
		msg.append("\r\n");
		msg.append("total count is connection pool: " + getConnectionCount());
		msg.append("\r\n");
		msg.append("not used connection count: " + getNotUsedConnectionCount());
		msg.append("\r\n");
		msg.append("used connection, count: " + getUsedConnectionCount());
		out.println(msg);
		Iterator iterator = m_usedUsedConnection.iterator();
		while (iterator.hasNext()) {
			ConnectionWrapper wrapper = (ConnectionWrapper) iterator.next();
			wrapper.debugInfo.printStackTrace(out);
		}
		out.println();
	}

	public static synchronized int getNotUsedConnectionCount() {
		return m_notUsedConnection.size();
	}

	public static synchronized int getUsedConnectionCount() {
		return m_usedUsedConnection.size();
	}

	public static synchronized int getConnectionCount() {
		return m_notUsedConnection.size() + m_usedUsedConnection.size();
	}

	public static String getUrl() {
		return m_url;
	}

	public static void setUrl(String url) {
		if (url == null) {
			return;
		}
		m_url = url.trim();
	}

	public static String getUser() {
		return m_user;
	}

	public static void setUser(String user) {
		if (user == null) {
			return;
		}
		m_user = user.trim();
	}

	public static String getPassword() {
		return m_password;
	}

	public static void setPassword(String password) {
		if (password == null) {
			return;
		}
		m_password = password.trim();
	}

}

class ConnectionWrapper implements InvocationHandler {
	private final static String CLOSE_METHOD_NAME = "close";
	public Connection connection = null;
	private Connection m_originConnection = null;
	public long lastAccessTime = System.currentTimeMillis();
	Throwable debugInfo = new Throwable("Connection initial statement");

	ConnectionWrapper(Connection con) {
		this.connection = (Connection) Proxy.newProxyInstance(
		con.getClass().getClassLoader(),
		new Class[]{Connection.class}, this);
		m_originConnection = con;
	}

	void close() throws SQLException {
		m_originConnection.close();
	}

	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable {
		Object obj = null;
		if (CLOSE_METHOD_NAME.equals(m.getName())) {
			ConnectionPool.pushConnectionBackToPool(this);
		} else {
			obj = m.invoke(m_originConnection, args);
		}
		lastAccessTime = System.currentTimeMillis();
		return obj;
	}

}

 

四.完成效果

首先user表是空的,然后在首页注册用户,然后查看数据库信息已经注册成功,再进行登陆,登陆成功后跳转到个人中心页面,修改密码手机等信息,完成后再次查看数据库

 

五.完整源代码包含jar包地址:

https://download.csdn.net/download/wcc27857285/10778616

 

PS后续:

我看了下大家都想要源代码和jar包地址,按原先的下载地址需要16个csdn积分,其实一开始我是随便设置的16积分、

后来我想改成免费的,但是无奈CSDN一波骚操作,我一通操作,还是改不了,所以我特地把代码放在了云盘上,供大家免费下载

 

链接:https://pan.baidu.com/s/1ccxDBkS_UaGX6Kw6uyM55A 
提取码:p4ls 
 

  • 14
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值