J2EE第三次作业

1.下载MySQL数据库

下载地址:https://dev.mysql.com/downloads/mysql/5.7.html#downlo

下载的是压缩包,下载到电脑后直接解压。可以把解压的内容随便放到一个目录,我的是如下目录(放到C盘的话,可能在修改ini文件时涉及权限问题,之后我就改放D盘了):

D:MySQLMySQL Server 5.7.22

如下图:此时加压后的文件中没有data目录和ini文件

在D:MySQLMySQL Server 5.7.22目录下新建my.ini文件,复制如下内容:

[mysqld]

port = 3306

basedir=D:MySQLMySQL Server 5.7.22

datadir=D:MySQLMySQL Server 5.7.22data

max_connections=200

character-set-server=utf8

default-storage-engine=INNODB

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

[mysql]

default-character-set=utf8

 Note:内容中红色部分是mysql的目录,上一部的那个路径

下面配置环境变量:

电脑属性-》高级系统设置-》

  点击环境变量

在系统变量部分新建一个变量名:MYSQL_HOME, 变量值:D:MySQLMySQL Server 5.7.22

 

 

MySQL安装过程:

管理员身份运行cmd

 

进入如下目录:D:MySQLMySQL Server 5.7.22in

运行命令:mysqld  --initialize (此时会生成data目录)

采坑:

如果运行命令提示:由于找不到MSVCR120.dll,无法继续执行代码.重新安装程序可能...

这种情况需要安装 vcredist 

下载vcredist :https://www.microsoft.com/zh-CN/download/details.aspx?id=40784

下载后,直接安装。

 运行mysqld -install (安装)

 运行net start mysql (启动mysql服务)

 可以在任务管理器中看到MySQL服务

设置root账户密码:

在my.ini文件(MySQL的配置文件)的[mysqld]下加一行skip-grant-tables

然后在任务管理器中重启MySQL服务

重启MqSQL服务后,运行mysql -uroot -p,可以成功登入mysql

然后更新root账户的密码为'root'

命令:update mysql.user set authentication_string=password("root") where user="root";

然后输入flush privileges;(刷新账户信息)

执行quit或ctrl+Z退出

然后将my.ini文件中刚才加的skip-grant-tables这一行删掉,保存后再重启MySQL服务

  然后运行mysql -uroot -proot就可以用root用户名和root密码登陆了

 下一步咱们下载一个可视化工具

 进入工具,登录刚配置好的数据库,账号是root,密码也是root

 在圈中部分右键点击空白区域建立数据库

 我已建立好一个名为first的数据库,然后该库中建立一个学生表,加入两个参数即可:stuName,stuPwd。分别代表学生姓名和学生密码。

 到此步数据库方面暂告一段落。

2.配置IEDA项目环境

建立New Project

 配置Tomcat

 选择应用服务器,这里咱们就用Tomcat。需要注意的是选择Tomcat目录到第一层目录即可。

进入MODULE设置。选Sources,在WEB-INF目录下创建两个新的文件夹classes和lib。

 进入Paths设置,将两个路径都改为刚才创建的classes文件夹

 进入Dependecies设置,点击右侧加号,添加项目依赖。

 选择JARs or directories,将前面建立好的lib文件夹进行依赖。

 继续添加依赖,我们选择第二项,将tomcat加入。

 至此,一个tomcat项目就配好了

3.连接数据库

package JDBCHelper;
import com.mysql.jdbc.StatementImpl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
 * 数据库连接
 */
public class MySqlDBUtil {
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/first?useSSL=true&characterEncoding=utf-8&user=root&password=root");
            System.out.println("数据库连接成功!");
            System.out.println("-------------------------------");
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("创建连接失败!");
        System.out.println("-------------------------------");
        return null;
    }
    public static void ShutDown(StatementImpl statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}

 结果展示:

 

 4.使用cookie,保存登录信息,30天内,用户无需登录

package Util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

public class CookieSave {
    public void Save(HttpServletResponse response,String name,String value,int last_time)
    {
        //创建Cookie,将用户名存到叫cookieUserName的cookie中
        //Cookie 对象携带需要保存的数据,user.getName()=value,都是字符串类型
        //每个cookie保存一个数据,如果需要多个,创建多个cookie对象
        Cookie cookieUserName = new Cookie(name, value);
        //设置cookie存在时间   单位:秒
        //cookie保存的时间,不管中途是否使用,访问cookie,到时就过期
        //如果不设置,那么cookie在浏览器关闭的时候失效
        cookieUserName.setMaxAge(last_time);
        //将cookie发给浏览器(如果没有这句,cookie就不会发送给客户端)
        response.addCookie(cookieUserName);
    }
}

查看Cookie,可以看到到期时间为7月4日。

 5.使用session,显示网站当前在线人数

package Servlet;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebListener()
public class OnlineCounterListener implements HttpSessionListener {
    //number of online
    public static int activeSessions = 0;

    /* Session创建事件 */
    public void sessionCreated(HttpSessionEvent se) {
        activeSessions++;
        System.out.println("newSession.id=" + se.getSession().getId() + "-->The number of online is " + Integer.toString(activeSessions));
        HttpSession session = se.getSession();
        // 获取 session 创建时间
        Date createTime = new Date(session.getCreationTime());
        //设置日期输出的格式
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("createtime=" + df.format(createTime));
        System.out.println("-------------------------------");

    }

    /* Session失效事件 */
    public void sessionDestroyed(HttpSessionEvent se) {
        activeSessions--;
        System.out.println("outSession.id=" + se.getSession().getId() + "-->The number of online is " + Integer.toString(activeSessions));
        HttpSession session = se.getSession();
        // 获取该网页的最后一次访问时间
        Date lastAccessTime = new Date(session.getLastAccessedTime());
        //设置日期输出的格式
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("The lastAccessTime " + df.format(lastAccessTime));
        System.out.println("-------------------------------");
    }
}

效果展示;

6.使用过滤器解决乱码问题,登录时用户名为中文可能不能正常识别,解决该问题

package Servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "GBFilter")
public class GBFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        String encoding =req.getCharacterEncoding();
        System.out.println("Before encoding "+encoding+" filter!");
        encoding="utf-8";//新编码
        req.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset="+encoding);
        System.out.println("after encoding "+encoding+" filter!");
        System.out.println("-------------------------------------");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    }
}

效果如下,可见乱码问题解决。

 7.上传码云:https://gitee.com/chenxingxin123/WEB.git

原文地址:https://www.cnblogs.com/565118008a/p/13042395.html