1. 程式人生 > >JSP實現登入註冊並連結資料庫頁面

JSP實現登入註冊並連結資料庫頁面

        在學習了頁面跳轉及部分知識後做了登入註冊介面,並經過本博主除錯bug後完善的更進一步,大家有什麼問題也可以留言,本博主以更廣泛學習討論為目的。

        內容介紹:實現頁面的跳轉;註冊登入時實現讀取資料庫,並對資料庫實現插入(insert)和查詢(select)功能。

        幾點注意:sqljdbc.jar包的匯入和環境變數;資料庫的登入讀取,可以參考資料庫的測試。

登入註冊介面的程式碼實現

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
    <center>
    <font face = "宋體" size = "6" color = "#000">歡迎使用飛龍科技</font><hr>
    <div>
        <img alt="" width = "600" height = "400" src="D:\我的圖片\QImages\小人團隊.jpg">
    </div>
    <table width = "200" border ="1" bordercolor = "#00F">
        <tr>
          <td><input type = "button" value = "登      陸" onclick = "window.location.href('login.jsp')"></td>
          <td><input type = "button" value = "注      冊" onclick = "window.open('register.jsp')"></td>
        </tr> 
    </table>
  </center>
  </body>
</html>

login.jsp  //登入介面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  <body>
    <center>
  	<font face="楷體" size="6" color="#000" >登入介面</font>
  	<%  
    String flag = request.getParameter("errNo");  
    try{
         if(flag!=null)
            out.println("使用者名稱不存在或密碼錯誤");
    }catch(Exception e){
        e.printStackTrace();
    }
   %>
  	<form action = "loginCh.jsp" method="post">
      <table width="300" height = "180" border="5" bordercolor="#A0A0A0"> 
 		<tr>
 		  <th>賬  戶:</th>
 		  <td><input type="text" name="name"  value = "請輸入使用者名稱" maxlength = "16" onfocus = "if(this.value == '請輸入使用者名稱') this.value =''"></td>
 	    </tr>
 	    <tr>
 		  <th>密  碼:</th>
 		  <td><input type="password" name="pwd" maxlength = "20"></td>
 	    </tr>
 	    <tr>
 	      <td colspan = "2" align = "center">
 		    <input type="submit" name="submit" value="登       錄">
 		    <input type="button" value="返       回"
 			  onclick="window.location.href('/webText')">
 	      </td>
 	    </tr>
 	  </table>
 	</form>
  </center>
  </body>
</html>
loginCh.jsp  //登入檢驗
<%@ page language="java" import="java.util.*,java.sql.*,java.net.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_loginCh.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%      //接收使用者名稱和密碼  
            String user = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");  
            String pwd = request.getParameter("pwd");

            String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
            String username = "sa";
            String password = "123";
            Class.forName(driverClass);//載入驅動 
            Connection conn = DriverManager.getConnection(url,username,password);//得到連線
            PreparedStatement pStmt = conn.prepareStatement("select * from tb_user where UName = '" + user + "' and Pwd = '" + pwd + "'");
              ResultSet rs = pStmt.executeQuery();
                if(rs.next()){
                    response.sendRedirect("success.jsp?username="+URLEncoder.encode(user)); //解決亂碼 
                }else{
                    response.sendRedirect("login.jsp?errNo");//密碼不對返回到登陸  
                }
     rs.close();
     pStmt.close();
     conn.close();
     %>
  </body>
</html>
success.jsp  //登入成功介面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Feilong_登入成功</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
    <center>
    <%
     String name = new String(request.getParameter("username").getBytes("8859_1"));
     out.println("歡迎你:" + name);
    %><br>
    <a href="login.jsp">重新登陸</a>
    </center>
  </body>
</html>

register.jsp  //註冊介面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'Feilong_register.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
    <script>
		function addCheck(){
			var username=document.getElementById("username").value;
			var password=document.getElementById("password").value;
			var newword=document.getElementById("newword").value;
			if(username==""){
				alert("使用者名稱不能為空!");
				document.getElementById("username").focus();  
				return false;
                }
			if(password==""){
				alert("密碼不能為空!");
				 document.getElementById("password").focus();
				 return false;
				 }
			if(password != newword){
				alert("兩次輸入密碼不相同!");
				 document.getElementById("newword").focus();
				 return false;
				 }
		}
		function validate(){
		    var flag = addCheck();
		    if(flag == false)
		        return false;
		    return true;
	    }
	</script>
  <body>
    <center>
	<font face="楷體" size="6" color="#000">註冊介面</font>
	<form action = "checkRegister.jsp" method = "post" onsubmit = "return validate()">
  	<table width="300" height = "180" border="5" bordercolor="#A0A0A0">
  	  <tr>
		<th>使用者名稱:</th>
		<td><input type="text" name="username" value="輸入16個字元以內" maxlength = "16" onfocus = "if(this.value == '輸入16個字元以內') this.value =''"></td>
 	  </tr>
 	  <tr>
 		<th>輸入密碼:</th>
 		<td><input type="text" name="password" value="輸入20個字元以內" maxlength = "20" onfocus = "if(this.value == '輸入20個字元以內') this.value =''"></td>
 	  </tr>
 	  <tr>
 		<th>確認密碼:</th>
 		<td><input type="text" name="newword" value="重新輸入密碼" maxlength = "20" onfocus = "if(this.value == '重新輸入密碼') this.value =''"></td>
 	  </tr>
	  <tr>
 		<td colspan = "2" align = "center">
 		  <input type="submit" value="注  冊">    
 		  <input type="reset" value="重  置">
 		</td>
	  </tr>
	</table>
    </form>
    </center>
  </body>
</html>
checkRegister.jsp //驗證註冊使用者並匯入資料庫
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_chechRegister.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%      
            String user = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8");  
            String pwd = request.getParameter("password");

            String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
            String username = "sa";
            String password = "123";
            Class.forName(driverClass);//載入驅動 
            Connection conn = DriverManager.getConnection(url,username,password);//得到連線
            PreparedStatement pStmt = conn.prepareStatement("select * from tb_user where UName = '" + user + "'");
              ResultSet rs = pStmt.executeQuery();
                if(rs.next()){
                    out.println("<script language='javascript'>alert('該使用者已存在,請重新註冊!');window.location.href='register.jsp';</script>");
                }else{
                    PreparedStatement tmt = conn.prepareStatement("Insert into tb_user values('" + user + "','" + pwd + "')");
                        int rst = tmt.executeUpdate();
                        if (rst != 0){
                              out.println("<script language='javascript'>alert('使用者註冊成功!');window.location.href='index.jsp';</script>");  
                        }else{
                           out.println("<script language='javascript'>alert('使用者註冊失敗!');window.location.href='register.jsp';</script>");  
                        }
                }
     %>
  </body>
</html>

以上程式碼若有問題,首先執行下面資料庫的測試程式碼:

執行下面程式碼前,首先在資料庫中建立名為‘db_01’的資料庫,在表中建立名為‘user’的表

login1.jsp

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%
    String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
    String username = "sa";
    String password = "123";
    Class.forName(driverClass);//這步錯可能是因為.jar包匯入問題
    Connection conn = DriverManager.getConnection(url,username,password);//這步錯可能是因為資料庫屬性安全中的名、密碼不對或SQL的IP埠不是‘1433’
    PreparedStatement pStmt = conn.prepareStatement("select * from tb_user");
           ResultSet rs = pStmt.executeQuery();
                while(rs.next()){
                      out.println("使用者名稱: " + rs.getString(1) 
                             + " 密碼: " + rs.getString(2));
                }
     rs.close();
     pStmt.close();
     conn.close();
     %>
  </body>
</html>

小人團隊.jpg

以上程式碼都是經過本博主細心敲打修改並實現的。轉載請註明本部落格的地址。

相關推薦

JSP實現登入註冊連結資料庫頁面

        在學習了頁面跳轉及部分知識後做了登入註冊介面,並經過本博主除錯bug後完善的更進一步,大家有什麼問題也可以留言,本博主以更廣泛學習討論為目的。        內容介紹:實現頁面的跳轉;註冊登入時實現讀取資料庫,並對資料庫實現插入(insert)和查詢(se

jsp實現登入註冊(與資料庫對接)

最近做了一些影象處理的內容,閒暇時間搞了下jsp,終於把至少兩個月之前的程式碼的bug找出來了... 具體內容我在之前一篇博文有介紹,主要是增加了資料庫的部分。其實一樣處理,獲得輸入的使用者名稱,密碼,然後判斷是否需要在當前頁面用javascipt處理下(比如註冊肯定是需要

javaEE之jsp+JavaBean實現登入+註冊+留言功能(外掛資料庫

javaEE之jsp+JavaBean實現登入+註冊+留言功能(外掛資料庫) 實現效果 #UserBean.java package nmx; public class UserBean { private String username; private Stri

實現登入註冊功能(連線資料庫)的JSP小專案

一、實現登入功能首先用sublime製作有表單檢查功能的login.html,程式碼具體如下:為了簡潔,我在Eclipse裡將CSS的引用方式改為鏈入式了,而接下來是在sublime剛做好後的程式碼截圖:然後將<form>改為<formaction="chk

C語言利用連結串列與檔案實現登入註冊

C語言實現簡登入和註冊功能 C語言實現註冊登入 使用連結串列 使用檔案 版本二:利用連結串列 此版本使用的連結串列,第一個版本使用的是陣列 陣列版本連線 這裡我使用的線性連結串列,一定要注意在判斷語句或賦值語句中不可將指標指向未定義的區域,這會產生很大問題,所以

bootstarp標籤頁實現登入註冊頁面

最簡單的實現樣式      <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <

java利用jdbc連線Mysql資料庫——實現登入註冊功能

實現功能如下: ①0選中註冊,若使用者名稱相同則註冊失敗,重新選擇 ②若使用者名稱不存在則儲存到資料庫 ③1選中登入,若使用者名稱和密碼符合時,登入成功。 程式碼如下: package com.lucfzy; import java.sql.Connection; imp

PHP PDO+MySQL實現登入註冊頁面

connect.php——連線資料庫,以後要連資料庫直接include,不用再一寫一大堆 <?php header("Content-type: text/html;charset=utf-8"); $dbh = new PDO("mysql:hos

jsp實現登入登入成功則跳轉到登入成功頁面,失敗則跳轉到失敗頁面

login.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8

bootstrap實現登入註冊介面

文章來自:原始碼線上https://www.shengli.me/css/65.html;   Bootstrap是一個Web前端開發框架,使用它提供的css、js檔案可以簡單、方便地美化HTML控制元件。Bootstrap框架為各種控制元件定義好了很多的類(class),在引入相

搭建自己的部落格(二十一):通過django表單實現登入註冊

1、變化的部分 2、上程式碼: {# 引用模板 #} {% extends 'base.html' %} {% load staticfiles %} {% block header_extends %} <link rel="stylesheet" h

JavaWeb+jsp+Mysql登入註冊

JavaWeb+jsp+Mysql登入註冊 List item 先需要匯入資料庫包 專案 1.login.jsp(登入介面) <%@ page language="java" import="java.util.*" pageEncod

JavaWeb實現登入註冊與驗證碼。

寫JavaWeb的準備工作: 首先準備好資料庫和Myeclipse,這裡以mysql為例,再下載好SQL的圖形化操作介面SQLyog,在資料庫中建張表 。 詳細步驟: 在Myeclipse 中新建一個Web工程: 在src下建三個包ServletPackge,ModelPac

react專案實現登入註冊

eact專案中實現登入註冊簡單粗暴感悟 全域性安裝react官方推薦腳手架 create-react-app npm install create-react-app -g 建立react專案 create-react-app react-login-register 進入專

純Servlet實現登入註冊

mysql資料庫user表的準備 javabean包中User類的建立 (1)uid,uname,upw,level四個私有屬性 (2)空參構造,滿參構造 (3)重寫get,set方法 (4)重寫hashcode()和equals方法,使用uid和uname控制 (5)重寫toString

ajax+springboot+mybits實現登入註冊功能

html程式碼 使用者名稱:<input type="text" placeholder="使用者名稱” id="form-username"> 密碼:<input type="password" placeholder="密碼" id

SSM框架下實現登入註冊

基本配置:jdk1.8   tomcat 8  MyEclipse 先打好地基:                    spring配置檔案 application.xml: <?xml version="1.0" encoding="UTF-8"?&g

Android使用MVP實現登入註冊

一.定義一個類(以下用到的介面) public class API { public static final String LOGIN_URL = "http://www.zhaoapi.cn/user/login";//登入介面 public

struts2簡單登入註冊程式(連線資料庫)

我用的是:struts2.3,tomcat7.0,oracle,編譯器intellij idea。 首先,開啟idea,找到file->new->project 根據圖中所指進行選擇,點選create找到struts下的lib路徑,找到以下核心jar包 接下來一路

android studio使用Bmob來實現登入註冊的功能

剛剛拋下了Eclipse,初學了android studio,一開始真是用起來感覺難受,不過的確能夠實現一些Eclipse不能實現的功能,而且用起來還蠻方便。 網上雖然有很多關於這等方面的教程,但是一些細節自己寫起來才發現存在很多問題。問題會在最後列出。 下面就詳細記錄一下