基於eclipse+servlet+jsp+jdbc+mysql登陸註冊功能(純淨版)

一、 建表

/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50717
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50717
File Encoding         : 65001

Date: 2017-04-14 11:12:39
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(16) NOT NULL,
  `password` varchar(16) NOT NULL,
  `repassword` varchar(16) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

二、話很少說,先上項目目錄結構

輸入圖片說明

(備註:本案例使用的是mysql數據庫,因此別忘記導入mysql-connector-java-5.1.8.jar)javascript

三、在src下新建util工具包,專門用來存放工具類,本案例的該包中主要存放jdbc數據庫鏈接類以及數據庫相關的配置文件,在util包中新建DBUtil類,代碼以下:

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;


/**
 *	管理鏈接的工具類,帶有鏈接池,
 *	適用於多線程的場景。
 */
public class DBUtil {	
	private static BasicDataSource ds;	
	//加載鏈接參數
	static {
		Properties p = new Properties();
		try {
			InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("util/db.properties");			
			p.load(is);
			is.close();			
			//讀取鏈接參數
			String driver = p.getProperty("jdbc.driver");
			String url = p.getProperty("jdbc.url");
			String user =p.getProperty("jdbc.user");
			String pwd = p.getProperty("jdbc.pwd");
			String initSize = p.getProperty("ds.initSize");
			String maxSize = p.getProperty("ds.maxSize");
			//建立鏈接池
			ds = new BasicDataSource();
			//設置鏈接參數(必須設置)
			ds.setDriverClassName(driver);
			ds.setUrl(url);
			ds.setUsername(user);
			ds.setPassword(pwd);
			//設置鏈接池管理參數(有默認值)
			//初始化鏈接數
			ds.setInitialSize(new Integer(initSize));
			//最大鏈接數
			ds.setMaxIdle(new Integer(maxSize));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("加載配置文件失敗", e);
		}
	}
	
	/**
	 * 鏈接池建立的鏈接,不是原始的鏈接,
	 * 而是它從新封裝後的鏈接。典型的特徵
	 * 是其關閉方法是歸還鏈接。
	 */
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("建立鏈接失敗", e);
		}
	}
	
	/**
	 * 若鏈接由鏈接池建立,則關閉鏈接
	 * 就是將其歸還給鏈接池,該鏈接的
	 * 狀態會變成空閒,能夠繼續複用。
	 */
	public static void close(
		Connection con, Statement smt) {
		try {
			if(smt != null) {
				smt.close();
			}
			if(con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("釋放資源失敗", e);
		}
	}

	public static void close(Connection con,Statement smt,ResultSet rs) {
		try {
				if(rs != null) {
					rs.close();
				}
				if(smt != null) {
					smt.close();
				}
				if(con != null) {
					con.close();
				}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("釋放資源失敗", e);
		}
	}	
	
	public static void main(String[] args) {
		Connection con = DBUtil.getConnection();
		System.out.println(con.getClass());
		DBUtil.close(con, null);
	}
	
}

四、在util包中新建一個db.properties文件,文件配置以下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.pwd=root
ds.initSize=3
ds.maxSize=5

五、在src下新建entity包,在entity包中新建實體類User,代碼以下:

package entity;

import java.io.Serializable;

public class User implements Serializable{
	
	private static final long serialVersionUID = 1L;

	private int id;
	private String username;
	private String password;
	private String repassword;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	

}

六、在src下新建dao包,在dao包中新建一個UserDao類,代碼以下:

package dao;

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

import entity.User;
import util.DBUtil;

public class UserDao {
	
	private Connection conn=null;
	private PreparedStatement ps=null;
	private ResultSet rs=null;
	private String sql="";
	
	/*
	 * 用戶登陸
	 */
	public boolean login(User user) throws SQLException {	
		boolean returnValue = false;
		conn = DBUtil.getConnection();
		sql="select * from user where username=? and password=?";
		ps = conn.prepareStatement(sql);
		ps.setString(1,user.getUsername());
		ps.setString(2,user.getPassword());
		rs=ps.executeQuery();
		if(rs.next()){
			returnValue=true;
			rs.close();
			ps.close();
		}else{
			returnValue=false;
			rs.close();
			ps.close();
		}
		conn.close();
		return returnValue;
	}
	/*
	 * 用戶註冊
	 */
	public boolean reg(User user) throws SQLException{
		boolean flag=false;
		conn=DBUtil.getConnection();
		sql="insert into user(username, password, repassword) values (?, ?, ?)";		
		int result = -1;// 表示當用戶執行添加刪除和修改的時候所影響數據庫的行數
		try {
			ps = conn.prepareStatement(sql);
			if(user == null) {
				return false;
			}
			ps.setObject(1, user.getUsername());
			ps.setObject(2, user.getPassword());
			ps.setObject(3, user.getRepassword());
			result = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		flag = result > 0 ? true : false;
		return flag;			
	}
		
	/*
     * 判斷用戶名在數據庫中是否存在
     */
    public boolean userIsExist(String username) throws SQLException{
        // 獲取數據庫鏈接Connection對象
        conn = DBUtil.getConnection();
        // 根據指定用戶名查詢用戶信息
        String sql = "select * from user where username = ?";
        try {
            // 獲取PreparedStatement對象
            PreparedStatement ps = conn.prepareStatement(sql);
            // 對用戶對象屬性賦值
            ps.setString(1, username);
            // 執行查詢獲取結果集
            ResultSet rs = ps.executeQuery();
            // 判斷結果集是否有效
            if(!rs.next()){
                // 若是無效則證實此用戶名可用
                return true;
            }
            // 釋放此 ResultSet 對象的數據庫和 JDBC 資源
            rs.close();
            // 釋放此 PreparedStatement 對象的數據庫和 JDBC 資源
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            // 關閉數據庫鏈接
            conn.close();
        }
        return false;
    }
}

七、在src下新建一個servlet包,在包中新建MainServlet,代碼以下:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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

import dao.UserDao;
import entity.User;

public class MainServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String path=req.getServletPath();
		if(path.equals("/toLogin.do")){
			//打開登陸頁
			toLogin(req,res);
		}else if(path.equals("/toReg.do")){
			//打開註冊頁
			toReg(req,res);
		}else if(path.equals("/login.do")){
			//登陸驗證
			login(req,res);
		}else if(path.equals("/reg.do")){
			//註冊驗證
			try {
				reg(req,res);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			throw new RuntimeException("404:頁面不存在!!!");
		}
	}	
	/*
	 * 打開登陸頁
	 */
	private void toLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {		
		String url="login.jsp";
		req.getRequestDispatcher(url).forward(req, res);
	}

	/*
	 * 打開註冊頁
	 */
	private void toReg(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		String url="reg.jsp";
		req.getRequestDispatcher(url).forward(req, res);
	}
	
	/*
	 * 登陸驗證
	 */
	private void login(HttpServletRequest req, HttpServletResponse res) throws IOException {
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/html");
		PrintWriter out=res.getWriter();
		String name=new String(req.getParameter("username"));
		String pwd=new String(req.getParameter("password"));
		User user=new User();
		user.setUsername(name);
		user.setPassword(pwd);
		UserDao dao=new UserDao();
		boolean isLogin;
		try {
			isLogin=dao.login(user);
			if(isLogin){
				req.getSession().setAttribute("name", name);
				res.sendRedirect("welcome.jsp");
			}else{
				res.sendRedirect("back.jsp");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 註冊驗證
	 */
	private void reg(HttpServletRequest req, HttpServletResponse res) throws IOException, SQLException {
		String path=req.getContextPath();
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/html");
		PrintWriter out=res.getWriter();		
		String username=req.getParameter("username"); 
		String password=req.getParameter("password");
		String repassword=req.getParameter("repassword");
		System.out.println("username:"+username+",password:"+password+",repassword:"+repassword);
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setRepassword(repassword);
		UserDao userDao=new UserDao();
		if(userDao.userIsExist(username)){					
			boolean flag=userDao.reg(user);			
				System.out.println("註冊成功!");
				req.getSession().setAttribute("username", username);
				res.sendRedirect("regOK.jsp");
			}
		else{
			System.out.println("註冊失敗(用戶名已存在)!");
			res.sendRedirect("regFail.jsp");
		}
			out.flush();
			out.close();			
		}	
}

到此後臺基本上處理完了,該收拾前臺頁面了!html

八、本案例一共有6個頁面,分別是:

  • 用來登陸的頁面login.jsp,代碼以下:
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
	function checkLogin(){
		var flag=true;
		var name=document.getElementById("name").value;
		var pwd=document.getElementById("pwd").value;
		if(""==name){
			alert("用戶名不能爲空!");
			flag=false;
			return false;
		}else if(""==pwd){
			alert("密碼不能爲空!");
			flag=false;
			return false;
		}if(flag==true){
			return true;
		}
	}
</script>
<title>登陸頁面</title>
</head>
<body>
	<center>歡迎登陸</center><br/>
	<center>
		<form action="login.do" method="post">
			用戶名:<input type="text" name="username" id="name" /><br /> 
			密&nbsp;&nbsp;&nbsp;&nbsp;碼:<input type="password" name="password" id="pwd" /><span style="color:red" id="pwdMsg"></span><br /> <br />
			<input type="submit" value="登陸" onclick="return checkLogin();"/>
			<input type="button" value="註冊" onclick="location='reg.jsp'"/> 
		</form>
	</center>
</body>
</html>

- 用來顯示登陸成功的頁面welcome.jsp,代碼以下:

<%@ page import="java.util.*" language="java"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登陸成功</title>
</head>
<body>
	<center><font color="red">${sessionScope.name },歡迎你!登錄成功!</font><br>
		<%
			Date today = new Date();
			int d = today.getDay();
			int h = today.getHours();
			String s = "";
			if (h > 0 && h < 12)
				s = "上午好";
			else if (h >= 12)
				s = "下午好";
			String day[] = { "日", "一", "二", "三", "四", "五", "六" };
			out.println(s + ",今天是星期" + day[d]);
		%>
	</center>
</body>
</html>

- 用來顯示登陸失敗的頁面back.jsp,代碼以下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登陸失敗</title>
</head>
<body>
<center>登陸失敗</center>
<center>用戶名或密碼錯誤,單擊<a href="login.jsp"><font color="red">這裏</font></a>返回</center>
</body>
</html>

- 用來實現註冊的頁面reg.jsp,代碼以下:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
	function checkReg(){
		var flag=true;
		var name=document.getElementById("name").value;
		var pwd=document.getElementById("pwd").value;
		var rePwd=document.getElementById("rePwd").value;
		if(""==name){
			alert("用戶名不能爲空!");
			flag=false;
			return false;
		}else if(""==pwd){
			alert("密碼不能爲空!");
			flag=false;
			return false;
		}else if(""==rePwd){
			alert("請再次輸入密碼以確認!");
			flag=false;
			return false;
		}else if(pwd!=rePwd){
			alert("兩次輸入的密碼不同,請從新輸入!");
			flag=false;
			return false;
		}if(flag==true){
			return true;
		}
	}
</script>
<title>註冊頁面</title>
</head>
<body>
	<center>歡迎註冊</center><br/>
	<center>
		<form action="reg.do" method="post">
			用戶名:<input type="text" name="username" id="name" /><br /> 
			密&nbsp;&nbsp;&nbsp;&nbsp;碼:<input type="password" name="password" id="pwd" /><br />
			重複密碼:<input type="password" name="repassword" id="rePwd"/><br/><br/>
			<input type="submit" value="提交" onclick="return checkReg();"/>
			<input type="button" value="返回" onclick="location='login.jsp'"/>
		</form>
	</center>
</body>
</html>

- 用來顯示註冊成功頁面regOK.jsp,代碼以下:

<%@page import="java.util.*" language="java"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>註冊成功</title>
</head>
<body>
	<center><font color="red">恭喜你,${sessionScope.username }!註冊成功!</font></center><br/>
	<center><a href="login.jsp">當即登陸!</a></center>
</body>
</html>

-用來顯示註冊失敗頁面regFail.jsp,代碼以下:

<%@page import="java.util.*" language="java"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>註冊失敗</title>
</head>
<body>
	<center><font color="red">註冊失敗:用戶名已存在!</font></center><br/>
	<center><a href="reg.jsp">從新註冊!</a></center>
</body>
</html>

**_java

OK,到此整個項目就算完結啦, 但千萬別忘了,要想讓其跑起來,還有咱們很是重要的web.xml文件的配置哦!

_**mysql

  • web.xml文件的配置以下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>jsj</display-name>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>servlet.MainServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MainServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>  
</web-app>

OVER,讓項目飛起來!!!web

相關文章
相關標籤/搜索