第十五篇——JDBC操作数据库之Cookie技术

在开发网站应用程序的过程中,使用cookie记录用户的一些信息是比较常用的一种方法,而cookie的使用也非常简单。

一、 前言 
说起来,Cookie应该是一种应用较久的技术了。早在HTML刚刚出现的时候,在每个独立的页面之间没有办法记录和标识不同的用户。后来人们就发明了 Cookie技术,当用户访问网页时,它能够在访问者的机器上创立一个文件,我们把它叫作Cookie,写一段内容进去,来标识不同的用户。如果下次用户 再访问这个网页的时候,它又能够读出这个文件里面的内容,这样网页就知道上次这个用户已经访问过该网页了。

虽然现在网页的制作技术比起几年以前已经发展了许多。不过有些时候,Cookie还是能够帮我们很多忙的。


二、 Cookie给网站和用户带来的好处

 1、Cookie能使站点跟踪特定访问者的访问次数、最后访问时间和访问者进入站点的路径
 2、Cookie能告诉在线广告商广告被点击的次数,从而可以更精确的投放广告
   3、Cookie有效期限未到时,Cookie能使用户在不键入密码和用户名的情况下进入曾经浏览过的一些站点

   4、Cookie能帮助站点统计用户个人资料以实现各种各样的个性化服务


本章将实现第3:Cookie有效期限未到时,Cookie能使用户在不键入密码和用户名的情况下进入曾经浏览过的一些站点


三、 步骤说明
1、代码请参考——第十四篇JDBC操作数据库之登录功能

2、在第十四篇基础上继续实现功能——第十五篇JDBC操作数据库之Cookie技术。

------------------------------------------------------------------------------------------------------

一.loginUser.jsp

1.获取cookie数组---获取值

2.注意用户名和密码的value属性

3.添加CheckBox

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ page import="java.net.URLDecoder" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>用户登录</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    <link rel="stylesheet" type="text/css" href="css/userStyle.css">


</head>

<body>
<%
    String username = "";
    String password = "";

    //获取cookie数组
    Cookie[] cookies = request.getCookies();
    if(cookies != null && cookies.length>0){
        for(Cookie cookie : cookies){
            //获取值
            if(cookie.getName().equals("username")){
                username = cookie.getValue();
                System.out.println("loginCookie username: " + username);
            }
            if(cookie.getName().equals("password")){
                password = cookie.getValue();
                System.out.println("loginCookie password: " + password);
            }
        }
    }
%>
<div class="border">
    <div class="head">登录用户</div>
    <div class="div1">
        <ul>
            <li><a href="registerUser.jsp"> 用户注册 |</a></li>
            <li><a href="loginUser.jsp"> 用户登录 |</a> </li>
            <li><a href="message.jsp"> 当前用户 |</a></li>
            <li><a href="cookie.jsp"> 查看cookie |</a></li>
            <li><a href="ExitLogin"> 退出登录 |</a></li>
        </ul>
    </div>
    <div class="div2">
        <form action="<%=request.getContextPath()%>/LoginUser" method="post" οnsubmit="return login(this)">
            <table align="center" width="300" border="0">
                <tr>
                    <td align="right">用户名:</td>
                    <td><input type="text" name="username" value="<%=username%>"></td>
                </tr>
                <tr>
                    <td align="right">密码:</td>
                    <td><input type="text" name="password" value="<%=password%>"></td>
                </tr>
                <tr>
                    <td colspan="2" align="center" height="50">
                        <input type="checkbox" name="isUseCookie">十天内记住我的登录状态
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center" height="50">
                        <input type="submit" value="登录">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>


二.LoginUser.java

1.先判断用户是否选择记住登录状态

2.创建Cookie对象数组

3.设置生存期限

4.保存cookie

package com.control;

import com.entity.User;
import com.model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Ray on 2018/3/14 0014.
 **/
public class LoginUser 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 password = request.getParameter("password");



        /**
        * @Author: Ray
        * @Date: 2018/3/15 0015
        * @Description: Cookie
        */
        //首先判断用户是否选择了记住登录状态
        String[] isUseCookies = request.getParameterValues("isUseCookie");
        if(isUseCookies != null && isUseCookies.length > 0){
            System.out.println("选择了记住登录状态!");
            //以键值对创建一个Cookie
            Cookie usernameCookie = new Cookie("username",username);
            Cookie passwordCookie = new Cookie("password",password);

            //设置最大生存期限为10天
            usernameCookie.setMaxAge(864000);
            passwordCookie.setMaxAge(864000);

            //保存Cookie
            response.addCookie(usernameCookie);
            response.addCookie(passwordCookie);
        }else{
            System.out.println("没有选择记住登录状态!");
            //创建一个Cookie对象数组
            Cookie[] cookies = request.getCookies();
            if(cookies != null && cookies.length > 0 ){
                for(Cookie cookie : cookies){
                    //判断元素的值是否为username和password中的值
                    if(cookie.getName().equals("username") || cookie.getName().equals("password")){
                        //设置Cookie失效
                        cookie.setMaxAge(0);
                        //重新保存
                        response.addCookie(cookie);
                    }
                }
            }
        }

        //调用模型
        UserDao userDao = new UserDao();
        //调用登录方法
        User user = userDao.login(username,password);
        if(user != null){
            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("message.jsp").forward(request,response);
        }else{
            request.setAttribute("info","错误:用户名或密码有误!");
            request.getRequestDispatcher("message.jsp").forward(request,response);
        }
    }
}

三.cookie.jsp(用于观察cookie状态)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ page import="java.net.URLDecoder" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>查看cookie</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">

    <link rel="stylesheet" type="text/css" href="css/userStyle.css">

</head>

<body>
<%
    String username = "";
    String password = "";

    //将所有的Cookie防盗一个Cookie对象数组里
    Cookie[] cookies = request.getCookies();
    if(cookies != null && cookies.length > 0){
        for(Cookie cookie : cookies){
            //获取值
            if(cookie.getName().equals("username")){
                //获取cookie的内容
                username = cookie.getValue();
                System.out.println("cookie username: " + username);
            }
            if(cookie.getName().equals("password")){
                password = cookie.getValue();
                System.out.println("cookie password: " + password);
            }
        }
    }
%>
<div class="border">
    <div class="head">查看cookie</div>
    <div class="div1">
        <ul>
            <li><a href="registerUser.jsp"> 用户注册 |</a></li>
            <li><a href="loginUser.jsp"> 用户登录 |</a> </li>
            <li><a href="message.jsp"> 当前用户 |</a></li>
            <li><a href="cookie.jsp"> 查看cookie |</a></li>
            <li><a href="ExitLogin"> 退出登录 |</a></li>
        </ul>
    </div>
    <div class="divreg">
        用户名:<%=username%>
        <br>
        <br>
        密码:<%=password%>
    </div>
</body>
</html>


四.页面效果











ok!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
播报频率和波形参数。我们可以使用百度语音合成API来实现语音合成,该API使用 JDBC 连接 Access 数据库,需要先下载 Microsoft 的 JDBC-ODBC 驱动,然后进行以下步骤: 1.可以将文本转换为语音,并以MP3格式进行下载。我们可以使用以下代码来实现语音合成 安装 Access 数据库并创建一个数据库文件(后缀为 .mdb 或 .accdb)。 2. 下载并安装: ```python import urllib.request import json def text_to_speech(text, filename): api_key = 'Your API Key Microsoft Access Database Engine。 3. 在系统的 ODBC 数据源管理器中添加一个数据源,选择 Microsoft Access Driver (*.mdb, *.accdb)。 4. 按照提示填写数据源名称和数据库文件路径等信息。 5. 在 Java 代码中使用 JDBC 连接 Access 数据库,示例代码如下: ```java import java.sql.*; public class AccessJDBC { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 加载 JDBC 驱动 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // 连接数据库 String url = "jdbc:odbc:myAccessDB"; String user = ""; String password = ""; conn = DriverManager.getConnection(url, user, password); // 执行 SQL 查询 String sql = "SELECT * FROM myTable"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); // 处理查询结果 while (rs.next()) { System.out.println(rs.getString("id") + ", " + rs.getString("name")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭资源 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ``` 其中,url 参数的值应该与 ODBC 数据源管理器中设置的数据源名称相同。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值