[狂神说]JavaWeb入门到实战 (二)

十三.过滤器、监听器常见应用

监听器:GUI编程中经常使用;

package com.kk.listener;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class TestPant {
    public static void main(String[] args) {
        Frame frame = new Frame("好好学习天天向上"); //新建一个窗体
        Panel panel = new Panel();//面板
        frame.setLayout(null);//设置窗体的布局

        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255));//设置背景颜色

        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,255,0));//设置背景颜色

        frame.add(panel);
        frame.setVisible(true);

//        监听事件  监听关闭事件

/*
        frame.addWindowListener(new WindowListener() {
            public void windowOpened(WindowEvent e) {
                System.out.println("打开");
            }

            public void windowClosing(WindowEvent e) {
                System.out.println("关闭Ing");
                System.exit(0);
            }

            public void windowClosed(WindowEvent e) {
                System.out.println("关闭ed");
            }

            public void windowIconified(WindowEvent e) {

            }

            public void windowDeiconified(WindowEvent e) {

            }

            public void windowActivated(WindowEvent e) {
                System.out.println("激活");
            }

            public void windowDeactivated(WindowEvent e) {
                System.out.println("未激活");
            }
        });
*/

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });

    }
}

用户登录后才能进入主页,注销后不能进入主页了!

  1. 用户登陆后,在Session中放入用户的数据
  2. 进入主页的时候要判断用户是否已经登陆;   要求:(在过滤器中实现)
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) request1;
        HttpServletResponse response = (HttpServletResponse) response1;

        if(request.getSession().getAttribute("USER_SESSION")==null){
            response.sendRedirect("/error.jsp");
        }
        chain.doFilter(request,response);
    }

项目思路:

  1. 首先进入等登录页面,走一个请求 (form重点的action)
  2. 请求走完,获取前端传递的用户名后,进行判断,正确或者失败
  3. 成功的话进入成功页面,并且创建session,失败的话进入失败页面
  4. 在成功页面设置注销按钮,注销按钮会移除Session
  5. 最后设置权限验证,加一个过滤器,过滤器解决了在未登录情况可以直接访问登录成功页面的情况。
package com.kk.filter;

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

public class SysFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) request1;
        HttpServletResponse response = (HttpServletResponse) response1;

        if(request.getSession().getAttribute("USER_SESSION")==null){
            response.sendRedirect("/error.jsp");
        }
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}
package com.kk.servlet;

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

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取前端请求的参数
        String username = req.getParameter("username");
        if (username.equals("admin")){
            req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else {
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
package com.kk.servlet;

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

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user_session = req.getSession().getAttribute("USER_SESSION");
        if(user_session!=null){
            req.getSession().removeAttribute("USER_SESSION");
            resp.sendRedirect("/login.jsp");
        }else{

        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注意:web.xml中需要配置拦截器和serlvet

十四.JDBC

什么是JDBC?

需要jar包的支持:

  • java.sql
  • javax.sql
  • mysql-connter-java 连接驱动(必要时候导入)

CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01')
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01')
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01')

SELECT *  FROM users;




Asia/Shanghai

useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai

导入数据库依赖

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
    </dependencies>

idea连接数据库

JDBC 固定步骤:

  1. 加载驱动
  2. 连接数据库,代表数据库
  3. 向数据库发送SQL的对象Statement:CRUD
  4. 编写SQL(根据业务,不同的SQL)
  5. 执行SQL
  6. 关闭连接(rs,statement,connection都要关)

package com.kk.test;

import java.sql.*;

public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
//        useUnicode=true&characterEncoding=utf-8解决中文乱码
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
        String username="root";
        String password="123456";


        //        1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //        2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);


        //        3.向数据库发送SQL的对象statement:CRUD
        Statement statement = connection.createStatement();

        //        4.编写SQL
        String sql="select * from users";

        //        5.执行查询SQL,返回一个结果集
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("id="+rs.getObject("name"));
            System.out.println("id="+rs.getObject("password"));
            System.out.println("id="+rs.getObject("email"));
            System.out.println("id="+rs.getObject("birthday"));
        }

//        关闭连接,释放资源(一定要做)  先开后关
        rs.close();
        statement.close();
        connection.close();
    }
}

增删改(executeUpdate)都是返回一个int类型的数据(受影响的行数)

预编译sql

package com.kk.test;

import java.sql.*;

public class Testjdbc2 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
        String username="root";
        String password="123456";

//       1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
//        2.连接数据库,代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

//        3.编写sql
        String sql="insert into users(id, name, password, email, birthday)values (?,?,?,?,?)";

//        4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,4);/*给第一个占位符赋值为1*/
        preparedStatement.setString(2,"kk学java");/*给第一个占位符赋值为1*/
        preparedStatement.setString(3,"123456");/*给第一个占位符赋值为1*/
        preparedStatement.setString(4,"86870805@qq.com");/*给第一个占位符赋值为1*/
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));/*给第一个占位符赋值为1*/


//        5.执行SQL
        int i = preparedStatement.executeUpdate();

        if (i>0){
            System.out.println("插入成功");
        }
//        6.关闭连接 释放资源
        preparedStatement.close();
        connection.close();
    }

}

事务

要么都成功、要么都失败!

ACID原则:保证数据的安全。

  1. 开启事务
  2. 事务提交 commit()
  3. 事务回滚  rollback()
  4. 关闭事务

转账:

A:1000

B:1000

A(900)  ---》100---》 B(1100)

A与B应该同事发生,如果出现错误,不能发生A减了100,但B没加的现象

Junit单元测试

依赖

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

简单实用

@Test注解只有在方法上有效,只要加了这个注解的方法究竟可以直接运行

失败的时候是红色

在更新数据库表时候添加事务

package com.kk.test;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Testjdbc3 {

    @Test
    public void test() {
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "123456";
        Connection connection=null;

//        1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");

//        2.连接数据库,代表数据库
 connection = DriverManager.getConnection(url, username, password);

 //        3.通知数据库开启事务 false开启
            connection.setAutoCommit(false);

            String sql = "update account set money=money-100 where name='A'";
            connection.prepareStatement(sql).executeUpdate();
//       4.制造错误
//            int i = 1 / 0;

            String sql2 = "update account set money=money+100 where name='B'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit();/*以上两条sql都执行成功,就提交事务*/
            System.out.println("success");
        } catch (Exception e) {
            try {
                /*如果出现异常 就通知数据库回滚事务*/
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值