1. 程式人生 > >javaweb簡單登入介面訪問mysql

javaweb簡單登入介面訪問mysql

概述:實現登入功能,使用者輸入帳號和密碼,通過form表單提交至後臺處理,查詢資料庫,如果使用者名稱和密碼均正確,則彈框提示使用者登入成功,否則提示登入失敗。

開發工具:eclipse Mars.2 Release (4.5.2)
伺服器 :apache-tomcat-7.0.68
資料庫:MySql

效果圖:


專案結構圖:


前臺原始碼:用到了簡單的 bootstrap 和 jquery

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html >
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<!--修正IE瀏覽器渲染效果的問題-->
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<!--內容自適應-->
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="css/bootstrap.css" type="text/css" >
	<script type="text/javascript" src="js/jquery.js"></script>
	<title>使用者登入</title>
	<!-- 點選重置按鈕清空使用者名稱和密碼 -->
	<script>
		$(document).ready(function(){
			$("#reset").click(function(){
				$("#username").val("");
				$("#pwd").val("");
			});
		});
	</script>
</head>
<body>
	<div class="row text-center" style="padding-top:30px; padding-bottom:30px; background-color: #CCC; margin-top:200px;">
		<form action="LoginServlet" method="post">
			<div class="col-md-6 col-md-offset-3">
				<div>
					<label>帳號:</label> 
					<input type="text" id="username" name="username" />
				</div>
				<div>
					<label class="img-circle">密碼:</label> 
					<!-- name很中要,用於後臺獲取值,一般class修飾樣式,id在js中用 -->
					<input class="input" id="pwd" name="pwd" type="password" />
				</div>
				<div style="margin:10px 0px;">
					<input class="btn btn-primary" type="submit" value="登入" /> 
					<input class="btn btn-group" id="reset" type="button" value="重置" />
				</div>
			</div>
		</form>
	</div>
	<script type="text/javascript" src="js/jquery.js"></script>
</body>
</html>

後臺程式碼:使用了servlet
package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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.mysql.jdbc.Connection;

/**
 * Servlet implementation class LoginServlet
 */
//如果在web.xml中宣告過servlet 就把這一句註釋掉
//@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        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 {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		
		//mysql資料庫驅動
		String driver = "com.mysql.jdbc.Driver";
		//連結資料庫的url test為資料庫名
		String url = "jdbc:mysql://127.0.0.1:3306/test";
		//資料庫使用者
		String user = "root";
		//資料庫密碼/在這裡輸入資料庫密碼
		String password = "123456";
		
		//從前臺讀取到的使用者名稱
		String username = request.getParameter("username");
		//從前臺讀取到的密碼
		String pwd = request.getParameter("pwd");
		
		//資料庫連結成功時返回的例項
		Connection conn = null;
		//查詢成功時返回的記錄集
		ResultSet rs = null;
		try{
			//載入驅動
			Class.forName(driver);
			//獲取連結
			conn = (Connection) DriverManager.getConnection(url, user, password);
			//準備sql查詢
			String sql = "select * from User where username=? and pwd=?";
			//使用PreparedStatement,可以防止sql注入
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, pwd);
			//執行查詢,返回記錄集 
			rs = ps.executeQuery();
			//如果查詢到使用者名稱和密碼,則允許使用者登入
			if (rs.next()){
				System.out.println("login ok!!");
				PrintWriter out = response.getWriter();
				out.flush();
				out.println("<script>");
				out.println("alert('恭喜,登入成功');");
				out.println("history.back();");
				out.println("</script>");
				out.close();
			}else{
				System.out.println("login fail!!");
				PrintWriter out = response.getWriter();
				out.flush();
				out.println("<script>");
				out.println("alert('很遺憾,使用者名稱或密碼錯誤');");
				out.println("history.back();");
				out.println("</script>");
				out.close();
			}
			//關閉PreparedStatement
			ps.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//最後一定要關閉連結
			if (conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		doGet(request, response);
	}

}

web.xml配置檔案:用於配置寫好的servlet, 如果servlet中有@WebServlet("/LoginServlet")則不用再配置,否則會產生錯誤。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>mysqlTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <servlet>
	    <description></description>
	    <display-name>LoginServlet</display-name>
	    <servlet-name>LoginServlet</servlet-name>
	    <servlet-class>com.test.LoginServlet</servlet-class>
    </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>