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,其完整的目錄結構如下所示 -

Servlet登錄實例

以下是這個項目中的幾個主要的代碼文件。

  • 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/ ,如果沒有錯誤,應該會看到以下結果 -

Servlet登錄實例

登錄成功後的界面,如下所示 -

Servlet登錄實例