JSP+sevlet實現登錄注冊功能(eclipse、SQL server數據庫操作)


一、問題描述

設計一個登錄界面,若是老用戶,則顯示用戶名、密碼、出生年月、性別、照片;

若是新用戶,則提供注冊頁面,包括用戶名、密碼、出生年月、性別、照片。

將用戶的信息保存到數據庫中,其中照片僅將文件名保存在表中,圖片保存在服務器的img目錄中。 

二 、實現思路 

三、實現步驟

1、創建數據庫。 為了避免用戶注冊時使用重復的用戶名,這里要將用戶的name設為主鍵。

2、創建前端的頁面,文件名為log.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登錄注冊頁面</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <div class="container right-panel-active">
        <!-- 登錄 signin-->
        <div class="container__form container--signin">
            <form action="./Log.jsp" class="form" id="form2" method="post">
                <h2 class="form__title">歡迎登錄</h2>
                <input type="text" placeholder="用戶名" class="input" name="user"/>
                <input type="password" placeholder="密碼" class="input" name="psd"/>
                <input type = "submit" value="登錄" class="btn">
            </form>
        </div>
 <!-- 注冊 signup-->
        <div class="container__form container--signup">
        <!-- 上傳文件表單enctype屬性必須為“multipart/form-data” -->
            <form action="/myproject/upLoad" class="form" id="form1" method="post" enctype="multipart/form-data"> 
                <h2 class="form__title">注冊賬號</h2>
                <input type="text" placeholder="用戶名" class="input" name="user1"/>
                <input type="password" placeholder="密碼" class="input" name="psd1"/>
                <input type="text" placeholder="性別" class="input" name="sex"/>
                <input type="text" placeholder="出生日期" class="input" name="birth"/>
                上傳照片
                <input type="file"  class="input" name="pic">
                <input type = "submit" value="注冊" class="btn">
            </form>

        </div>
        <!-- 疊加部分 -->
        <div class="container__overlay">
            <div class="overlay">
                <div class="overlay__panel overlay--left">
                    <button class="btn" id="signIn">已有賬號,直接登錄</button>
                </div>
                <div class="overlay__panel overlay--right">
                    <button class="btn" id="signUp">沒有賬號,點擊注冊</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="./script.js"></script>
</html>

3. 裝飾一下HTML,創建他的css文件,命名為“style.css”


:root {
	
	--white: #e9e9e9;
	--gray: #333;
	--blue: #0367a6;
	--lightblue: #008997;


	--button-radius: 0.7rem;

	--max-width: 758px;
	--max-height: 520px;
	font-size: 16px;
	font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
		Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

body {


	align-items: center;

	background-color: var(--white);

	background: url("bg.jpeg");

	background-attachment: fixed;

	background-position: center;

	background-repeat: no-repeat;

	background-size: cover;

	display: grid;

	height: 100vh;

	place-items: center;
}

.form__title {
 
    font-weight: 300;
    margin: 0;
	margin-bottom: 1.25rem;
}


.link {
	color: var(--gray);
	font-size: 0.9rem;
	margin: 1.5rem 0;
	text-decoration: none;
}

.container {
	background-color: var(--white);
    border-radius: var(--button-radius);
    

	box-shadow: 0 0.9rem 1.7rem rgba(0, 0, 0, 0.25),
        0 0.7rem 0.7rem rgba(0, 0, 0, 0.22);
        
	height: var(--max-height);
	max-width: var(--max-width);
	overflow: hidden;
	position: relative;
	width: 100%;
}


.container__form {
	height: 100%;
	position: absolute;
	top: 0;
	transition: all 0.6s ease-in-out;
}

.container--signin {
	left: 0;
	width: 50%;
	z-index: 2;
}

.container.right-panel-active .container--signin {
	transform: translateX(100%);
}

.container--signup {
	left: 0;
	opacity: 0;
	width: 50%;
	z-index: 1;
}

.container.right-panel-active .container--signup {
	animation: show 0.6s;
	opacity: 1;
	transform: translateX(100%);
	z-index: 5;
}

.container__overlay {
	height: 100%;
	left: 50%;
	overflow: hidden;
	position: absolute;
	top: 0;
	transition: transform 0.6s ease-in-out;
	width: 50%;
	z-index: 100;
}

.container.right-panel-active .container__overlay {
	transform: translateX(-100%);
}

.overlay {
	background-color: var(--lightblue);
	background: url("bg.jpeg");
	background-attachment: fixed;
	background-position: center;
	background-repeat: no-repeat;
	background-size: cover;
	height: 100%;
	left: -100%;
	position: relative;
	transform: translateX(0);
	transition: transform 0.6s ease-in-out;
	width: 200%;
}

.container.right-panel-active .overlay {
	transform: translateX(50%);
}

.overlay__panel {
	align-items: center;
	display: flex;
	flex-direction: column;
	height: 100%;
	justify-content: center;
	position: absolute;
	text-align: center;
	top: 0;
	transform: translateX(0);
	transition: transform 0.6s ease-in-out;
	width: 50%;
}

.overlay--left {
	transform: translateX(-20%);
}

.container.right-panel-active .overlay--left {
	transform: translateX(0);
}

.overlay--right {
	right: 0;
	transform: translateX(0);
}

.container.right-panel-active .overlay--right {
	transform: translateX(20%);
}

.btn {
	background-color: var(--blue);
	background-image: linear-gradient(90deg, var(--blue) 0%, var(--lightblue) 74%);
	border-radius: 20px;
	border: 1px solid var(--blue);
	color: var(--white);
	cursor: pointer;
	font-size: 0.8rem;
	font-weight: bold;
	letter-spacing: 0.1rem;
	padding: 0.9rem 4rem;
	text-transform: uppercase;
	transition: transform 80ms ease-in;
}

.form > .btn {
	margin-top: 1.5rem;
}

.btn:active {
	transform: scale(0.95);
}

.btn:focus {
	outline: none;
}

.form {
	background-color: var(--white);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	padding: 0 3rem;
	height: 100%;
	text-align: center;
}

.input {
	background-color: #fff;
	border: none;
	padding: 0.9rem 0.9rem;
	margin: 0.5rem 0;
	width: 100%;
}

@keyframes show {
	0%,
	49.99% {
		opacity: 0;
		z-index: 1;
	}

	50%,
	100% {
		opacity: 1;
		z-index: 5;
	}
}

4. 創建JavaScript文件,命名為“script.js”

// 獲取元素和點擊操作
const signInBtn = document.getElementById("signIn");
const signUpBtn = document.getElementById("signUp");
const fistForm = document.getElementById("form1");
const secondForm = document.getElementById("form2");
const container = document.querySelector(".container");

signUpBtn.addEventListener("click", () => {
	container.classList.add("right-panel-active");
});

signInBtn.addEventListener("click", () => {
	container.classList.remove("right-panel-active");
});

前端效果

                                                     

5.登錄功能判斷頁面。命名為"Log.jsp"

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用戶名密碼檢驗</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
//創建數據庫連接
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=user";
String user="sa";
String password="123456";
Connection conn = DriverManager.getConnection(url,user,password);
Statement stmt = null;
ResultSet rs = null;

String name = request.getParameter("user");
String psd = request.getParameter("psd");
String sql_1 = "select * from user01 where name='"+ name+ "'";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql_1);
//如果數據庫中存在該用戶
if(rs.next()){
	String real_psd = rs.getNString("password").trim();
	if(psd.equals(real_psd)){
		out.println("登錄成功");
	}
	else{
		out.println("密碼錯誤");
	}
}else{
	out.println("用戶名不存在");
}
%>
</body>
</html>

6.登錄功能頁面,命名為“upLoad.java”

package com.mypackage;

import java.io.IOException;

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 java.util.List;
import java.util.Iterator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;




/**
 * Servlet implementation class upLoad
 */
@WebServlet("/upLoad")
public class upLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public upLoad() {
        super();
        // 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
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
	

		String []data= new String[5];//創建一個數組,用於存放非文件類型的數據,以及文件名
		//上傳文件
		try {
	        //得到上傳文件的保存目錄。 將上傳的文件存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全
	        String realPath = this.getServletContext().getRealPath("/img");//  /WEB-INF/files
	        System.out.println("文件存放位置:"+realPath);
	        //設置臨時目錄。 上傳文件大於緩沖區則先放於臨時目錄中
	        String tempPath = "D:\\tempFile";
	        System.out.println("臨時文件存放位置:"+tempPath);


	        //判斷存放上傳文件的目錄是否存在(不存在則創建)
	        File f = new File(realPath);
	            if(!f.exists()&&!f.isDirectory()){
	                System.out.println("目錄或文件不存在! 創建目標目錄。");
	                f.mkdir();
	            }
	        //判斷臨時目錄是否存在(不存在則創建)
	        File f1 = new File(tempPath);
	            if(!f1.isDirectory()){
	                System.out.println("臨時文件目錄不存在! 創建臨時文件目錄");
	                f1.mkdir();
	            }

	       /**
	        * 使用Apache文件上傳組件處理文件上傳步驟:
	        *
	        **/
	        //1、設置環境:創建一個DiskFileItemFactory工廠
	        DiskFileItemFactory factory = new DiskFileItemFactory();

	            //設置上傳文件的臨時目錄
	        factory.setRepository(f1);

	        //2、核心操作類:創建一個文件上傳解析器。
	        ServletFileUpload upload = new ServletFileUpload(factory);
	            //解決上傳"文件名"的中文亂碼
	        upload.setHeaderEncoding("UTF-8");

	        //3、判斷enctype:判斷提交上來的數據是否是上傳表單的數據
	        if(!ServletFileUpload.isMultipartContent(request)){
	            System.out.println("不是上傳文件,終止");
	             //按照傳統方式獲取數據
	            return;
	        }
        //==獲取輸入項==
	            //限制單個上傳文件大小3M)
	            upload.setFileSizeMax(1024*1024*3);
           //限制總上傳文件大小(3M)
          upload.setSizeMax(1024*1024*3);

	        //4、使用ServletFileUpload解析器解析上傳數據,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
	            List<FileItem> items =upload.parseRequest(request);
	            System.out.println();
	            
	            for(int i=0;i<items.size();i++){
	            	FileItem item = items.get(i);
	            	
	                //如果fileitem中封裝的是普通輸入項的數據(輸出名、值)
	                if(item.isFormField()){
	                    String filedName = item.getFieldName();//普通輸入項數據的名
	                    //解決普通輸入項的數據的中文亂碼問題
	                    String filedValue = item.getString("UTF-8");//普通輸入項的值
	                    data[i]=filedValue;
	                    System.out.println(data[i]);
	                    
	                }else{
	                    //如果fileitem中封裝的是上傳文件,得到上傳的文件名稱,
	                    String fileName = item.getName();//上傳文件的名
	                    //將文件名寫入數組中 
	                    data[4]=fileName;                  	                    
	                    //多個文件上傳輸入框有空 的 異常處理
	                    if(fileName==null||"".equals(fileName.trim())){  //去空格是否為空
	                        continue;// 為空,跳過當次循環,  第一個沒輸入則跳過可以繼續輸入第二個
	                    }

	                    //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如:  c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt
	                    //處理上傳文件的文件名的路徑,截取字符串只保留文件名部分。//截取留最后一個"\"之后,+1截取向右移一位("\a.txt"-->"a.txt")
	                    fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
	                    //拼接上傳路徑。存放路徑+上傳的文件名
	                    String filePath = realPath+"\\"+fileName;
	                    //構建輸入輸出流
	                    InputStream in = item.getInputStream(); //獲取item中的上傳文件的輸入流
	                    OutputStream out = new FileOutputStream(filePath); //創建一個文件輸出流

	                    //創建一個緩沖區
	                    byte b[] = new byte[1024];
	                    //判斷輸入流中的數據是否已經讀完的標識
	                    int len = -1;
	                     //循環將輸入流讀入到緩沖區當中,(len=in.read(buffer))!=-1就表示in里面還有數據
	                    while((len=in.read(b))!=-1){  //沒數據了返回-1
	                    //使用FileOutputStream輸出流將緩沖區的數據寫入到指定的目錄(savePath+"\\"+filename)當中
	                        out.write(b, 0, len);
	                    }
	                    //關閉流
	                    out.close();
	                    in.close();
	                    //刪除臨時文件
	                    try {
	                        Thread.sleep(3000);
	                    } catch (InterruptedException e) {
	                        e.printStackTrace();
	                    }
	                    item.delete();//刪除處理文件上傳時生成的臨時文件
	                    System.out.println("文件上傳成功");
	                }
	    
	            }
	        } catch (FileUploadException e) {
	            e.printStackTrace();
	            throw new RuntimeException("服務器繁忙,文件上傳失敗");
	        }
		
        //連接數據庫,並將數據寫入數據庫中
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} 
		String url = "jdbc:sqlserver://localhost:1433;DatabaseName=user";
		String user="sa";
		String password="123456";
		//
		PreparedStatement pstmt = null;
		ResultSet rs = null;	
		try {
			Connection conn = DriverManager.getConnection(url,user,password);
			String sql = "insert into user01 values(?,?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,data[0]);
			pstmt.setString(2,data[1]);
			pstmt.setString(3,data[2]);
			pstmt.setString(4,data[3]);
			pstmt.setString(5,data[4]);
			pstmt.executeUpdate();
			conn.close();
			//頁面跳轉
			request.getRequestDispatcher("/reg_success.jsp").forward(request,response);
		} catch (SQLException e1) {
			e1.printStackTrace();
			response.sendError(response.SC_NOT_FOUND,e1.getMessage());
			}
	
	}

	}

7.創建注冊成功后的跳轉頁面,命名為“reg_success.jsp”

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>注冊成功</title>
</head>
<body>
注冊成功
</body>
</html>

8.eclipse工程文件目錄

這里有幾個包需要導入

四、問題總結

1.環境問題

ServletFileUpload.isMultipartContent(request)方法需要用Tomcat8.5版本(10以下應該可以),原來用的Tomcat10,一直說我沒有導入包。

2.文件上傳

(1)form表單enctype屬性必須為“multipart/form-data”才能上傳文件,但在此情況下無法用request.getParameter()獲取非文件數據。

(2)form表單中<input type="file">框里顯示的內容跟瀏覽器有關,有些會將路徑也顯示出來,有些則只顯示文件名。建議使用谷歌瀏覽器。

3.數據庫操作

在執行數據庫操作時,這里用到了兩種方法創建

方法一:creatStatement()

stmt = conn.createStatement();
rs = stmt.executeQuery(sql_1);

方法二:preparedStatement()

PreparedStatement pstmt = null;
ResultSet rs = null;	
try {
		Connection conn = DriverManager.getConnection(url,user,password);
		String sql = "insert into user01 values(?,?,?,?,?)";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1,data[0]);
		pstmt.setString(2,data[1]);
		pstmt.setString(3,data[2]);
		pstmt.setString(4,data[3]);
		pstmt.setString(5,data[4]);
		pstmt.executeUpdate();

 方法二在參數設置上靈活性更好。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM