1. 程式人生 > >JSP+Servlet+JavaBean+JDBC實現使用者登入,及成績查詢

JSP+Servlet+JavaBean+JDBC實現使用者登入,及成績查詢

用Myeclipse新建web專案jsp+javabean,具體功能如下:

A.       建立與資料表相對應的javabean

B.       建立一個使用者登入頁面 ,輸入使用者名稱和密碼;

C.       建立一個連線資料庫、及資料庫操作的javabean(DateDao),用來連線資料庫、執行資料庫操作

D.       登入頁面提交時,servlet使用DateDao進行登入驗證;登入成功跳轉到顯示登入使用者成績的頁面,登入失敗跳轉到登入頁面;


1、建立Bean

package com.Server;

import java.io.Serializable;

public class Student implements Serializable 
{
private int student_id;
private String student_name;
private int student_password;
 

public Student(String name,int password)
{
	this.student_name=name;
	this.student_password=password;
}



public void setStudent_id(int student_id) 
	{
	this.student_id = student_id;
	}
public int getStudent_id() 
	{
	return student_id;
	}



public void setStudent_name(String student_name) 
	{
	this.student_name = student_name;
	}
public String getStudent_name()
	{
	return student_name;
	}




public void setStudent_password(int student_password)
	{
	this.student_password = student_password;
	}
public int getStudent_password()
	{
	return student_password;
	}


}


2、使用者登入介面JSP、顯示成績JSP

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>  
<%@ page import="com.Server.Student"%> 



<!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>


<form action="check_servlet" method="post">
<center>
<table width="446" height="298" border="1">
  <tr>
    <td colspan="2" align="center">登入頁面</td>
</tr>
  <tr>
    <td  width="92" align="center">使用者名稱:</td>
    <td width="232"><input type="text" name="studentname"></td>
  </tr>
  <tr>
    <td align="center">密碼:</td>
    <td><input type="password" name="studentpassword"></td>
  </tr>
  
  <tr>
    <td colspan="2" align="center"><input type="submit" value="登入"></td>
  </tr>
</table>
</center>
</form>


</body>
</html>

<%@page import="java.awt.Window"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  
    <title>顯示結果頁面</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  </head>

  
  <%
  String message = "";
  String Sid = request.getParameter("Sid");
  String getjava = request.getParameter("getjava");
  String c = request.getParameter("c");
  
  System.out.println(Sid+"score頁面");
  String flag = request.getParameter("flag");
  if(flag!=null&&flag.equals("success"))
  {
  	message = "登入成功!";
  }else if(flag!=null&&flag.equals("false"))
  {
  	message = "登入失敗!";
  	Sid = "無";
  	getjava = "無";
  	c = "無";	 
    }
 	 %>
   
   

  <body onload="jump()">
  
  <center>
  <%=message %><br>
  ID:<%=Sid %><br>
  Java成績:<%=getjava %><br>
  c++成績:<%=c %><br>
  <a href="student_login.jsp">返回登陸</a>
 
  </center> 
 
    <script type="text/javascript">
  
  function jump()
  {
	  if(flag==false)
	 <%
	 
	 %>
			  
   }
  
  </script>
  
  
  
  </body>
</html>


3、DateDao.java 連線資料庫及操作

package com.Server;

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

public class DateDao
{

	
	public static Connection con = null;//定義連線
	public static Statement st = null;//定義statement
	public ResultSet result = null;//定義結果集 
	public static String driver;//定義驅動   
    public static String url;//定義URL   
    public static String user;//定義使用者名稱   
    public static String password;//定義密碼     
  
	//建立與資料庫連線的函式  
	    public Connection getConn(){  
	    	try { 
	    		
		    	driver="com.mysql.jdbc.Driver";
		    	url="jdbc:mysql://localhost:3306/test2";
		    	user="root";
		    	password="";
	            
					Class.forName(driver);
				   
	            con = DriverManager.getConnection(url,user,password);//獲取資料庫連線
	            System.out.println("-------連線成功------");
	            }  
	    	catch (SQLException e) 
	        {
	        	e.printStackTrace();
			} 
	    	catch (ClassNotFoundException e) 
	    	{	
				e.printStackTrace();
			} 
	    	return this.con;   
	    }   
	    
	    
	public DateDao()
	{

		this.con=this.getConn();
		//建構函式,預設加裁配置檔案為jdbc.driver
	}
	
	
 
	 // 執行資料庫查詢並返回查詢結果
	 public  ResultSet query(String sql)
	 {
		 this.con=this.getConn();
		 try 	{
				st = con.createStatement();//獲取Statement
				result = st.executeQuery(sql);//執行查詢,返回結果集				
				 } catch (Exception e)
					 {
				e.printStackTrace();
					 }
		return result;
	 }
	 
	 
	 //執行資料庫更新  
	    public void update(String sql)
	    {  
	    	this.con=this.getConn();
		 try 	{	
				st = con.createStatement();//獲取Statement
				st.executeUpdate(sql);//執行查詢,返回結果集				
				 } catch (Exception e)
					 {
				e.printStackTrace();
					 }
	    }  
	 

	    
	  //關閉資料庫連線  
	    public void close(){  
	        try{  
	            if (result != null)result.close();  
	            if (st != null)st.close();   
	            if (con != null)con.close();  
	        }catch(Exception ex){  
	            ex.printStackTrace();  
	        }         
	    } 
	
	
}

4、Servlet呼叫DateDao操作資料庫
package Servlet;

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

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

import com.Server.DateDao;
import com.Server.Student;

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


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		 
		 
		
		DateDao mysql = new DateDao();
		String context = request.getContextPath();
		
		
		
          
        String username = new String(request.getParameter("studentname").getBytes("iso-8859-1"),"utf-8"); 
        Integer userpassword = Integer.parseInt(request.getParameter("studentpassword"));
        
 
        System.out.println(username);
        System.out.println(userpassword);
        
       
        String sql = "select*from student where Sname='"+username+"' and Password='"+userpassword+"'";  
        
        Student student= new Student(username,userpassword);
         
     	
        	//驗證登入
        	ResultSet rs = mysql.query(sql);                      
            try {
				if (rs.next()){              	
					
					//獲取該成員ID
					Integer Sid = rs.getInt("Sid");
					System.out.println(Sid);
					mysql.close();//關閉連線
					
					//通過ID查詢該成員成績
					
					Integer getjava = 0;
					Integer c = 0;
						
					String scoresql = "select*from score where Sid ='"+Sid+"'";
					ResultSet rs1 = mysql.query(scoresql);
						
					if(rs1.next())
						{
						
						getjava = rs1.getInt("Java");
						System.out.println(getjava);
						
						c = rs1.getInt("c");
						System.out.println(c);
						
						mysql.close();//關閉連線
						}	
					response.sendRedirect(context+"/student_score.jsp?flag=success&Sid="+Sid+"&getjava="+getjava+"&c="+c); 
					
				}else{  
					  
					mysql.close();
					response.sendRedirect(context+"/student_score.jsp?flag=false&Sid=null"); 
     	
				}
			} catch (SQLException e) {
			
				e.printStackTrace();
			}                     
        
     
                                                                               
    
	}

}