1. 程式人生 > >servlet+jsp+MySQL實現簡單的頁面登陸

servlet+jsp+MySQL實現簡單的頁面登陸

由於對於前端的程式碼不熟悉,頁面登陸介面會比較簡陋,請見諒。

本部落格為本人自學後自行嘗試的實戰,若有錯誤,望指出,不勝感激。

在eclipse中,整個專案結構如下:


login.jsp用於登陸,register.jsp用於註冊,welcome.jsp為登陸後的介面

linkdb.java主要用來連線資料庫,程式碼如下:

package secondsfj;

import java.sql.DriverManager;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class linkdb {
        public static final String db="com.mysql.jdbc.Driver";
        public static final String url="jdbc:mysql://localhost:3306";
        public static final String user="root";
        public static final String password="9999999";
        private  Connection conn;
        
        public  void linkdatabase()
        {
			try {
				Class.forName(db);
				conn=(Connection) DriverManager.getConnection(url,user,password);
				} catch (ClassNotFoundException e) {
				System.out.println("載入資料庫類失敗");
				} catch (SQLException e) {
				 System.out.println("連線資料庫失敗");
				}
        }
        
        public  Connection getconn()
        {
        	return conn;
        }
        
        public  void close()
        {
        	try {
				if(!conn.isClosed())conn.close();
			} catch (SQLException e) {
				System.out.println("關閉資料庫連線失敗");
			}
        }
}

controldb.java主要用於資料庫的操作,程式碼如下:

package secondsfj;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;
import secondsfj.linkdb;

public class controldb {
      private Statement state=null;
      private ResultSet res = null;
      linkdb deal=new linkdb();
      
       public  void dealcontroldb()//連線資料庫,建立SQL語句物件
      {
    	  try {   		  
    		  deal.linkdatabase();
			state=(Statement) (deal.getconn()).createStatement();
		      } catch (SQLException e) {
			       System.out.println("建立SQL語句失敗");
		      }
    	  hasdb();
      }
      
       void hasdb()//判斷資料庫是否存在,不存在,進行建立
      {
    	  
    	  String temp;
    	  boolean x=false;
    	 try {
			res=state.executeQuery("show databases;");
			while(res.next())
			{
				temp=res.getString(1);
				if(temp.equals("login"))
				{
					
					x=true;
					break;
				}
			}
			if(x==false)
			{
				state.execute("create database login;");
				state.execute("use login;");
				state.execute("create table user (username char(20),password char(20));"); 
			}
		} catch (SQLException e) {
			System.out.println("controldb中的SQL語句執行失敗");
		} 
      }
      
      public  boolean verify(String username,String password)//用於驗證登陸
      {
    	  String usertemp;
    	  String passtemp;
    	  if(username==null||password=="null"||"".equals(username)||"".equals(password)) return false;
    	  try {
    		state.execute("use login;");
			res=state.executeQuery("select * from user");
			while(res.next())
			{
			     usertemp=res.getString(1);
			     if(usertemp.equals(username))
			     {
			    	 passtemp=res.getString(2);
			    	 if(passtemp.equals(password)) return true;   		 
			     }
			}
		} catch (SQLException e) {
			System.out.println("verify中的SQL語句執行失敗");
		}
    	  return false;
      }
      
      public  boolean register(String user,String passwd)//用於註冊
      {
    	  if(user==null||passwd==null||"".equals(user)||"".equals(passwd)) return false;
    	  try {
    		 state.execute("use login;");
			 state.execute("insert into user(username,password) values("+user+","+passwd+");");
		} catch (SQLException e) {
			System.out.println("register中的SQL語句執行失敗");
			return false;
		} 
    	  return true;
      }
      
      public  void close()//關閉連線
      {
    	  try {
			if(!state.isClosed())state.close();
			if(!res.isClosed())res.close();
			deal.close();
		} catch (SQLException e) {
			System.out.println("controldb關閉失敗");
		}   	  
      }
}

servletforlogin用於處理登陸介面的post請求,程式碼如下:

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 secondsfj.controldb;
import secondsfj.linkdb;

@WebServlet(displayName="servletforlogin", urlPatterns={"/servletforlogin"})
public class servletforlogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
    public servletforlogin() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("user");
        String password=request.getParameter("password");
        controldb temp=new controldb();
        temp.dealcontroldb();
        boolean x=temp.verify(username, password);
        String error=null;
        if(x==false) 
        {
        	error="使用者名稱或是密碼錯誤";
        	request.setAttribute("error", error);
            request.getRequestDispatcher("login.jsp").forward(request, response);	
        }
        else
        {
        	response.sendRedirect("welcome.jsp");
        }
        temp.close();
	}

}

servletforregister負責註冊,程式碼如下:

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 secondsfj.controldb;
import secondsfj.linkdb;


@WebServlet(displayName="servletforregister",urlPatterns={"/servletforregister"})
public class servletforregister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
    public servletforregister() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("user");
        String password=request.getParameter("password");
        controldb deal=new controldb();
        deal.dealcontroldb();
        String error=null;
        boolean x=deal.register(username, password);
        if(x==false)
        {
            error="密碼或是使用者名稱為空";
            request.setAttribute("error", error);
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
        else  response.sendRedirect("login.jsp");
        	
        deal.close();	
	}

}

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">
<title>登陸</title>
</head>
<body>
<%
String deal=(String)request.getAttribute("error");
if(deal!=null)
	out.println(deal);
%>
<form action="servletforlogin" method="post">
使用者:<input type="text" name="user"/>
<br>
<br>
密碼:<input type="password" name="password"/>
<br>
<br>
<input type="submit" value="提交">
</form>
<br>
<br>
<button onclick="{location.href='/secondsfj/register.jsp'}">註冊</button>
</body>
</html>

register.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>
<%
   String error=(String)request.getAttribute("error");
   if(error!=null)
	   out.println(error);
%>
<form  action="/secondsfj/servletforregister" method="post">
使用者:<input type="text" name="user"/>
<br/>
<br/>
密碼:<input type="password" name="password"/>
<br/>
<br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

welcome.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>Insert title here</title>
</head>
<body>
歡迎!!!!!
</body>
</html>

執行過程如下,先註冊後登陸:





若我們登陸時輸入錯誤的使用者或密碼,會出現錯誤提示:


注意到url處不為login.jsp,因為我們呼叫的是forward,此時位址列的url不會發生改變。

若我們註冊時只輸入空格或不輸入就按提交,會出現如下錯誤資訊


url欄不變原因同上。