servlet数据库验证登录

servlet数据库验证登录

一、将数据库连接和验证封装为一个单独的类

import java.sql.*;

public class SQLtest {
    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&" +
            "characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8";

    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "123456";

    public boolean mySql(String sname, String spassword) {
//    public static void main(String[] args) {
//        String sname = "user1";
//        String spassword="123456";
        Boolean success = false;
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT name,password FROM table_name ";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while (rs.next()) {
                // 通过字段检索
                String name = rs.getString("name");
                String password = rs.getString("password");

//                // 输出数据
//                System.out.println("用户名: " + name);
//                System.out.println("密码: " + password);
                if (name.equals(sname) && password.equals(spassword)) {
                    success = true;
                }
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
        System.out.println(success);
        return success;

    }
}

二、在web的验证函数中调用函数实现验证

import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(name = "CheckServlet",value = "/check")
public class CheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取表单的用户信息
        String username = request.getParameter("username");
        String userPassword =  request.getParameter("userPassword");
        SQLtest sqLtest = new SQLtest();
        boolean success = sqLtest.mySql(username,userPassword);
        //用全局初始化参数模拟数据库,并获取用户名保存在枚举中
//        Enumeration<String> arrayParam = getServletContext().getInitParameterNames();
//
//        //遍历枚举
//        while (arrayParam.hasMoreElements()){
//            //获取用户名和用户密码
//            String paramName = arrayParam.nextElement();
//            String paramValue = getServletContext().getInitParameter(paramName);
            /*
            * 校验登录信息,用户信息正确则重定向到主页,并设置Cookie的生命周期为30天
            * */

            if (success){
                Cookie cookie = new Cookie("user",username);
                cookie.setMaxAge(24*30*3600);
                response.addCookie(cookie);
                request.setAttribute("user",username);
//                System.out.println(request.getAttribute("user"));
                request.getRequestDispatcher("WEB-INF/main.jsp").forward(request,response);
            }
//        }
        //校验失败则返回登录界面
        HttpSession session =  request.getSession();
        session.setAttribute("name","wrong");
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }
}

效果展示:

 

成功登录:

登录失败:

 

特别说明:在web中运行时可能会遇到java.lang.ClassNotFoundException: com.mysql.jdbc.Driver异常,解决方法请关注我的另外一篇博文:https://www.cnblogs.com/xjtsh/p/10606548.html

 

百度网盘:链接: https://pan.baidu.com/s/1I3a3XAhGNez_ktsMn_GyTw 提取码: f85w 

 

posted @ 2019-03-27 12:38  、所剩无几  阅读(1700)  评论(0编辑  收藏  举报