JStudy Day18

今日学习

今天学习了监听器并复习了有关JDBC的内容,了解了过滤器、监听器的常见应用。
初步进入了狂神说SMBMS的框架搭建。

JavaBean

实体类
JavaBean有特定的写法:
1、必须要有一个无参构造
2、属性必须私有化
3、必须有对应的get/set方法
一般用来和数据库的字段做映射(ORM)

ORM:对象关系映射
1、表-》类
2、字段-》类属性
3、行记录-》对象

示例

package com.sea.pojo;

//实体类 我们一般和数据库中的表结构一一对应
public class People {
    private int id;
    private String name;
    private int age;
    private String address;

    public People() {
    }
    public People(int id, String name, int age, String address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

MVC三层架构

什么是MVC:Model View Controller 模型、视图、控制器

图解

JStudy Day18

Model:

1、业务处理:业务逻辑(Service)
2、数据持久层:CRUD(增删改查)(DAO)

View(JSP)

1、展示数据
2、提供链接发起的请求(a,form,img)

Controller(Servlet)

1、接收用户的请求:(req 请求参数、Session信息)
2、交给业务层处理对应的代码
3、控制视图的跳转

流程

登录->接收用户的请求->处理用户的请求(获取用户登录的参数(用户名密码))->交给业务层处理登录业务(判断用户名密码是否正确:事务)->DAO层查询用户名和密码是否正确->数据库

过滤器Filter(重点)

filter过滤器:用来过滤网站的数据
1、处理中文乱码
2、登录验证
JStudy Day18

Filter开发步骤:

1、导包(依赖)
2、编写过滤器
1、导包
2、重写方法
3、编写代码:实现Filter接口,重写其中方法即可

过滤器编写

package com.sea.filter;

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

public class CharacterEncodingFilter implements Filter {
    //初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化成功");
    }
    //Chain:链
    //1、过滤器中的所有代码在过滤特定请求的时候都会执行
    //2、必须要让过滤器继续通行 chain.doFilter(req,resp);
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");


        System.out.println("过滤器执行前");
        chain.doFilter(req,resp);//让我们的请求继续走,如果不写,程序到此拦截停止
        System.out.println("过滤器执行后");
    }
    //销毁:web服务器关闭的时候,过滤器销毁
    public void destroy() {
        System.out.println("销毁成功");
    }
}

配置filter(web.xml)

<filter>
    <filter-name>CharEnFilter</filter-name>
    <filter-class>com.sea.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharEnFilter</filter-name>
    <!--只要是/servlet的任何请求,都会经过这个过滤器-->
    <url-pattern>/ShowServlet/*</url-pattern>
</filter-mapping>

监听器

GUI编程中常用
实现一个监听器的接口(有N种)

流程:编写一个监听器:

1、实现监听器接口:

package com.sea.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计网站在线人数:统计Session
public class OnlineCountListener implements HttpSessionListener {
    //创建Session监听:看你的一举一动
    //一旦创建一个Session,就会触发一次事件
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();

        System.out.println(se.getSession().getId());

        Integer oc = (Integer) sc.getAttribute("OnlineCount");
        if (oc == null){
            oc = new Integer(1);
        }else{
            int count = oc.intValue();
            oc = new Integer(count + 1);
        }
        sc.setAttribute("OnlineCount",oc);
    }
    //销毁Session监听
    //Session销毁,就会触发一次事件
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();
        System.out.println(se.getSession().getId());
        Integer oc = (Integer) sc.getAttribute("OnlineCount");
        if (oc == null){
            oc = new Integer(0);
        }else{
            int count = oc.intValue();
            oc = new Integer(count - 1);
        }
        sc.setAttribute("oc",oc);
    }
}

2、配置监听器(web.xml)

<listener>
    <listener-class>com.sea.listener.OnlineCountListener</listener-class>
</listener>

过滤器、监听器常见应用

用户登录检测:
用户登录之后才能进入主页,注销之后就不能进入主页

1、用户登录之后向SESSION放入用户数据

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

2、进入主页的时候要判断用户是否已经登录:要求在过滤器中实现

public class SysFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //ServletRequest里没有getSession方法 所以需要转换为HttpServletRequest

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

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

JDBC复习

JStudy Day18
需要jar包支持:
1、java.sql
2、javax.sql
3、mysql-connector-java

固定步骤(statement):

1、加载驱动 (Class.forname)
2、连接数据库(DriverManager.getConnection)
3、创建向数据库发送SQL的对象Statement:CRUD
4、编写SQL
5、执行SQL ResultSet

固定步骤(prepareStatement):

1、加载驱动 (Class.forname)
2、连接数据库(DriverManager.getConnection)
3、编写SQL
4、创建向数据库发送SQL的对象prepareStatement,传入SQL进行预编译
5、调用prepareStatement对象方法传入参数
6、调用prepareStatement对象方法执行SQL语句

JDBC事务:Junit单元测试

依赖:

junit
junit
4.11

简单使用:
@Test只有在方法上使用,只要加了这个注解就可以测试,需要导包

SMBMS项目搭建(重点)

需求分析

JStudy Day18
项目如何搭建:考虑是否使用Maven,依赖,jar

项目搭建准备工作

1、搭建一个MavenWeb项目
2、配置Tomcat
3、测试项目是否能够运行
4、导入JAR包
jsp,servlet,mysql驱动,jstl,standard
5、创建项目包结构
JStudy Day18
6、编写实体类
ORM映射:表-类映射
示例:

package com.sea.pojo;

import java.math.BigDecimal;
import java.util.Date;

public class Bill {
    private Integer id;
    private String billCode;
    private String productName;
    private String productDesc;
    private String productUnit;
    private BigDecimal productCount;
    private BigDecimal totalPrice;
    private Integer isPayment;
    private Integer createBy;
    private Date creationDate;
    private Integer modifyBy;
    private Date modifyDate;
    private Integer provideId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBillCode() {
        return billCode;
    }

    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductDesc() {
        return productDesc;
    }

    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }

    public String getProductUnit() {
        return productUnit;
    }

    public void setProductUnit(String productUnit) {
        this.productUnit = productUnit;
    }

    public BigDecimal getProductCount() {
        return productCount;
    }

    public void setProductCount(BigDecimal productCount) {
        this.productCount = productCount;
    }

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Integer getIsPayment() {
        return isPayment;
    }

    public void setIsPayment(Integer isPayment) {
        this.isPayment = isPayment;
    }

    public Integer getCreateBy() {
        return createBy;
    }

    public void setCreateBy(Integer createBy) {
        this.createBy = createBy;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    public Integer getProvideId() {
        return provideId;
    }

    public void setProvideId(Integer provideId) {
        this.provideId = provideId;
    }

    public String getProviderName() {
        return providerName;
    }

    public void setProviderName(String providerName) {
        this.providerName = providerName;
    }

    private String providerName;//供应商名称
}

7、编写基础公共类

1、数据库配置文件 db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?serverTimezone=UTC&&useUnicode=true&&characterEncoding=utf8&&useSSL=false
user=root
password=123456
2、编写数据库的公共类
package com.sea.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//操作数据库的公共类
public class BaseDao {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //静态代码块 类加载的时候就初始化了
    static {
        Properties properties = new Properties();
        //通过类加载器读取对应的资源
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    //获取数据库连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    //编写查询公共类
    public static ResultSet execute(Connection connection, String sql,Object[] params,ResultSet resultSet,PreparedStatement ps) throws SQLException {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject占位符从1开始,但是数组是从0开始的
            ps.setObject(i + 1,params[i]);
        }
        resultSet = ps.executeQuery();
        return resultSet;
    }
    //编写CRUD公共方法
    public static int execute(Connection connection, String sql,Object[] params,PreparedStatement ps) throws SQLException {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject占位符从1开始,但是数组是从0开始的
            ps.setObject(i + 1,params[i]);
        }
        int updateRows = ps.executeUpdate();
        return updateRows;
    }
    //关闭链接 释放资源
    public static boolean release(Connection connection,PreparedStatement ps,ResultSet resultSet){
        boolean flag = true;
        if (resultSet != null){
            try {
                resultSet.close();
                //GC回收
                resultSet = null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }
        if (ps != null){
            try {
                ps.close();
                //GC回收
                ps = null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }
        if (connection != null){
            try {
                connection.close();
                //GC回收
                connection = null;
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                flag = false;
            }
        }
    }
}

3、编写字符编码过滤器

package com.sea.filter;

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

public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        chain.doFilter(req,resp);
    }

    public void destroy() {

    }
}

配置filter:

<!--字符编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.sea.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

END

明天继续深入SMBMS项目学习。
JStudy Day18

上一篇:JAVA Day18


下一篇:Day18_继承和邮件自动发送