Servlet登入範例


在這裡,我們將建立一個使用servlet建立登入表單的簡單範例,在這個範例中使用MySQL作為資料庫。

實現的主要功能:

  • 顯示登入表單輸入框(使用者名,密碼)。
  • 在表單中填寫使用者名,密碼並提交。
  • 在Servlet中接收提交的使用者名和密碼,與資料庫表中的資料進行比較。
  • 匹配使用者名和密碼,則提示成功;不匹配則提示失敗。

需要建立一個使用者表:servlet_user。 此外,它必須包含一些資料。表結構及資料記錄如下:

DROP TABLE IF EXISTS `servlet_user`;
CREATE TABLE `servlet_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL DEFAULT '',
  `passwd` varchar(32) NOT NULL DEFAULT '',
  `email` varchar(32) DEFAULT NULL,
  `city` varchar(24) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of servlet_user
-- ----------------------------
INSERT INTO `servlet_user` VALUES ('1', 'maxsu', '123456', '[email protected]', '廣州');
INSERT INTO `servlet_user` VALUES ('2', 'minsu', '233123', '[email protected]', '海口');
INSERT INTO `servlet_user` VALUES ('3', 'avguser', 'fdsa123', '[email protected]', '廣州');
INSERT INTO `servlet_user` VALUES ('4', 'sumuser', 'fdsj124', '[email protected]', '北京');

開啟Eclipse,建立一個動態Web專案:ServletLogin,其完整的目錄結構如下所示 -

以下是這個專案中的幾個主要的程式碼檔案。

  • index.html
  • LoginServlet.java
  • LoginDao.java
  • WelcomeServlet.java
  • web.xml

以下是各個檔案中的實現程式碼。

檔案:index.html -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用者登入範例</title>
</head>
<body>
    <div style="margin: auto; text-align: center;">
        <form action="login" method="post">
            使用者名:<input type="text" name="username" /> 密 碼:<input
                type="password" name="passwd" /> <input type="submit"
                value="登 錄" />
        </form>
    </div>
</body>
</html>

檔案:LoginServlet.java -

package com.yiibai.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.yiibai.dao.LoginDao;

public class LoginServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String passwd = request.getParameter("passwd");

        if (LoginDao.doLogin(username, passwd)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            RequestDispatcher rd = request.getRequestDispatcher("welcome");
            rd.forward(request, response);
        } else {
            out.print("使用者名或密碼錯誤~!");
            RequestDispatcher rd = request.getRequestDispatcher("index.html");
            rd.include(request, response);
        }
        out.close();
    }
}

檔案:LoginDao.java -

package com.yiibai.dao;

import java.sql.*;

public class LoginDao {

    public static boolean doLogin(String username, String passwd) {
        System.out.println("UserName : "+username+", Passwd:"+passwd);
        boolean status = false;
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useSSL=false&characterEncoding=utf8", "root", "123456");
            // 使用者名及密碼是否正確?
            PreparedStatement ps = con.prepareStatement("SELECT * FROM servlet_user WHERE name=? AND passwd=?");
            ps.setString(1, username);
            ps.setString(2, passwd);
            ResultSet rs = ps.executeQuery();
            status = rs.next();
        } catch (Exception e) {
            System.out.println(e);
        }
        return status;
    }
}

檔案:WelcomeServlet.java -

package com.yiibai.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

public class WelcomeServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        out.print("登入成功~!<br/>");
        out.print("歡迎您," + username);
        out.close();
    }

}

檔案:web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>ServletLogin</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.yiibai.servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>WelcomeServ</servlet-name>
        <servlet-class>com.yiibai.servlet.WelcomeServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>WelcomeServ</servlet-name>
        <url-pattern>/welcome</url-pattern>
    </servlet-mapping>
</web-app>

在編寫上面程式碼後,部署此Web應用程式(在專案名稱上點選右鍵->」Run On Server…」),開啟瀏覽器存取URL: http://localhost:8080/ServletLogin/ ,如果沒有錯誤,應該會看到以下結果 -

登入成功後的介面,如下所示 -