1. 程式人生 > 其它 >jsp、servlet、jdbc實現留言板(可記住密碼)

jsp、servlet、jdbc實現留言板(可記住密碼)

技術標籤:java-webmysqljdbcjspjavaservlet

文章目錄

使用工具:mysql、IDEA

一、目標

  • 留言板進行優化:
    登陸頁面輸入使用者名稱、密碼,提交給某個servlet,該servlet可以檢索資料庫,驗證使用者名稱和密碼是否合法,給出驗證結果

二、JDBC使用說明

  1. JDBC基本功能

     建立連線、傳送SQL語句,處理資料庫操作結果
    
  2. mysql使用

    (1)workbench–新建–schemas—create a new schema
    (2)使用:資料庫右鍵set default schema
    (3)新建表格

    (4)編輯表格 列:id欄位(專門)(長整數,自增編號),關係模型資料庫進行連線查詢根據id欄位完成,
    注:PK=primary key NN=not null AI=auto increment

  3. IDEA下載驅動

    將MYSQL-mysql-connector-java-8.0.18.jar複製到專案目錄下web的WEB_INF-lib下,並在File-Project Structure-Modules下新增該jar

  4. JDBC語句

//1.註冊資料庫的驅動
        try {
            Class.forName("com.mysql.jdbc.Driver"
); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.printf("載入驅動有錯誤"+e.getMessage()); } //2.獲取資料庫連線(裡面內容依次是:"jdbc:mysql://主機名:埠號/資料庫名?時區引數","使用者名稱","登入密碼") String dbURL = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"
; Connection connection = null;//放外面 try { connection = DriverManager.getConnection(dbURL,"root","root");//(資料庫連線,使用者名稱,密碼) } catch (SQLException throwables) { throwables.printStackTrace(); System.out.printf("生成連線物件有錯誤+"+throwables.getMessage()); } //3.建立語句物件 try { Statement statement = connection.createStatement(); //4.需要執行的語句 String sql = "select * from student"; ResultSet resultSet = statement.executeQuery(sql);//返回二維結果表 while(resultSet.next()){ //遍歷resultSet System.out.println("姓名:"+resultSet.getString("name")); System.out.println("年齡:"+resultSet.getInt("age")); } //5.關閉 statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }

三、程式碼

BoardLoginServlet.java(新)


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;

@javax.servlet.annotation.WebServlet(name = "BoardLoginServlet",urlPatterns = "/board")
public class BoardLoginServlet extends HttpServlet {

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

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset = utf-8");
        request.setCharacterEncoding("UTF-8");
        ServletContext context = request.getServletContext();
        HttpSession session=request.getSession();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        session.setAttribute("username",username);

        //1.註冊資料庫的驅動
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.printf("載入驅動有錯誤"+e.getMessage());
        }
        //2.獲取資料庫連線(裡面內容依次是:"jdbc:mysql://主機名:埠號/資料庫名","使用者名稱","登入密碼")
        String dbURL = "jdbc:mysql://localhost:3306/users?serverTimezone=UTC";
        Connection connection = null;//放外面
        try {
            connection = DriverManager.getConnection(dbURL,"root","root");//(資料庫連線,使用者名稱,密碼)
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.printf("生成連線物件有錯誤+"+throwables.getMessage());
        }
        //3.需要執行的sql語句
        String sql = "select * from pswd where name=?";
        String sql2 = "select * from pswd";
        //4.獲取預處理物件,並依次給引數賦值
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            ResultSet resultSet = statement.executeQuery();
            while(resultSet.next()){
                if(!(resultSet.getString("password").equals(password))) {
                    response.sendRedirect("board-error.jsp");
                    return;
                }else{
                    if ((request.getParameter("check") != null) && (request.getParameter("check").equals("check"))){
                        Cookie nameCookie = new Cookie("username", username);
                        Cookie pswdCookie = new Cookie("password", password);
                        nameCookie.setMaxAge(60 * 60);
                        pswdCookie.setMaxAge(60 * 60);
                        nameCookie.setPath("/");
                        pswdCookie.setPath("/");
                        response.addCookie(nameCookie);
                        response.addCookie(pswdCookie);

                        String value1 = "", value2 = "";
                        Cookie cookie = null;
                        Cookie[] cookies = request.getCookies();
                        if (cookies != null) {
                            for (int i = 0; i < cookies.length; i++) {
                                cookie = cookies[i];
                                if (cookie.getName().equals("username"))
                                    value1 = cookie.getValue();
                                if (cookie.getName().equals("password"))
                                    value2 = cookie.getValue();
                            }
                            ResultSet rs = statement.executeQuery(sql2);//返回二維結果表
                            while(rs.next()){    //遍歷resultSet
                                if (value1.equals(rs.getString("name")) && value2.equals(rs.getString("password"))) {
                                    response.sendRedirect("board-title.jsp");

                                    return;
                                } else {
                                    response.sendRedirect("board-title.jsp");
                                    return;
                                }
                            }
                        }
                    }
                    else {
                        response.sendRedirect("board-title.jsp");
                        return;
                    }
                }


            }
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }



    }
}

總結

在使用jdbc過程中出現過很多錯誤
例如使用try-catch後,登入後出現500
在這裡插入圖片描述
解決:在sendRedirect後加上return;

另外,此次增加了一個簡單的登陸失敗頁面。

程式設計小白,有錯誤請大佬指出…

繼續努力!!!








本人原創,歡迎轉載~