Javaweb(三)

Cookie、Session

会话

会话
用户打开浏览器,点击了很多超链接,方位多个web资源,关闭浏览器,这个过程成为会话
有状态会话: 一个同学来过教室,下次再来就会认识这个同学曾经来过,成为有状态会话
你怎么证明你购买了一件东西?
你 商店
1.发票 商店给你发票
2.登记 商店标记你来过
一个网站,怎么证明你来过?
客户端 服务端
1.服务端给客户端一个信件,客户端下次访问服务端带上信件就行;Cookie
2.服务器登记级你来过,下次登录匹配;session

保存会话的两种技术

cookie

  • 客户端技术(响应,请求)

session

  • 服务器技术,利用这个技术可以保存用于的会话信息,我们可以把信息或者数据放在session中

常见:网站登录之后,你下次不用再登陆,直接可以登录

image

1.从请求中拿到cookie信息
2.服务器相应给客户端cookie

Cookie[] cookies = req.getCookies(); //从服务器获得cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的value
new Cookie("time", System.currentTimeMillis()+"") //新建一个cookie
cookie.serMaxAge() //设置cookie有效期
resp.addCookie(cookie); //将cookie相应给服务器
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //服务器告诉你来的时间,把这个时间封装为一个信件,下次登陆带上
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");

    PrintWriter out = resp.getWriter();

    //Cookie,服务器端从客户端获取
    Cookie[] cookies = req.getCookies();//返回数组,说明Cookie可能存在多个
    //判断Cookie是否存在
    if(cookies!=null) {
        out.write("您上一次访问的时间是");
        for (int i=0;i< cookies.length;i++) {
            Cookie cookie = cookies[i];
            //获取cookie的名字
            if(cookie.getName().equals("time")) {
                //获取cookie的值
                long time = Long.parseLong(cookie.getValue());
                Date date = new Date(time);
                out.write(date.toLocaleString());
            }
        }
    }else{
        out.write("这是您第一次访问本站");
    }

    //服务端给客户端相应一个cookie
    Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");
    //cookie有效期为5s
    cookie.setMaxAge(5);
    resp.addCookie(cookie);
}

Session(重点)

image

什么是session:

  • 服务器会给每个用户(浏览器)创建一个session对象
  • 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
  • 用户登录之后,整个网站都可以访问 -->保存用户信息,保存购物车信息...

Session和Cookie的区别:

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存
  • Session把用户的数据写道用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
  • Session对象由服务器创建

使用场景:

  • 保存一个登陆用户的信息
  • 购物车信息
  • 在整个网站中进场会使用的数据,将其存在Session中

使用:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //解决乱码问题
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    //得到Session
    HttpSession session = req.getSession();
    session.setAttribute("name","大牛");
    //给Session存东西
    String id = session.getId();
    //判断Session是否为新创建的
    if(session.isNew()) {
        out.write("Session创建成功,id为"+id);
    }else {
        out.write("Session已经存在,id为"+id);
    }
}

MVC三层架构

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

早年架构

image
用户直接访问控制层,控制层就可以直接操作数据库
servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护。servlet代码中:处理请求、响应、试图跳转、处理JDBC、处理业务代码、处理逻辑代码

三层架构

image

Model

  • 业务处理:业务逻辑(Service)
  • 数据持久层:CRUD(Dao)

View

  • 展示数据
  • 提供链接,发起Servlet请求(a,form,img...)

Controller

  • 接受用户的请求(req:请求参数,Session信息)
  • 交给业务层处理对应的代码
  • 控制试图的跳转
    登录-->接受用户登录请求-->处理用户的请求(获取用户登陆参数,username,password)-->交给业务层处理登录业务(判断用户名密码是否正确)-->Dao层查询用户名和密码是否正确

Filter

Filter:过滤器,用来过滤网站的数据
image

  • 处理中文乱码
  • 登录验证

Filter开发步骤

1.导包

<dependencies>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

2.编写过滤器

  • 导包为servlet包
  • 实现doFilter方法
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("utf-8");
    servletResponse.setCharacterEncoding("utf-8");
    servletResponse.setContentType("text/html;charset=utf-8");

    System.out.println("CharacterEncodingFilter执行前");
    /*chain
    1.过滤中的所有代码,再过滤特定请求时都会执行
    2.必须让过滤器继续同行*/
    filterChain.doFilter(servletRequest,servletResponse);  //让我们的请求继续走,如果不写,程序到这里就被拦截停止了
    System.out.println("CharacterEncodingFilter执行后");
}

3.在web.xml中配置Filter过滤器

JDBC

public class TestJDBC {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //配置信息
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);
        //3.向数据库发送SQL的对象Statement
        Statement statement = connection.createStatement();
        //4.编写SQL
        String sql="SELECT * FROM `users`";
        //5.执行查询SQL,返回一个结果集
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()) {
            System.out.println("id+"+resultSet.getObject("id"));
            System.out.println("name+"+resultSet.getObject("name"));
            System.out.println("password+"+resultSet.getObject("password"));
            System.out.println("email+"+resultSet.getObject("email"));
            System.out.println("birthday+"+resultSet.getObject("birthday"));
        }
        //6.关闭连接,释放资源(一定)
        statement.close();
        connection.close();
    }
}
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,connection代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL的对象Statement
String sql="insert into `users` values (?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,4);
statement.setString(2,"李四");
statement.setString(3,"123456");
statement.setString(4,"ls@qq.com");
statement.setString(5, "2020-01-01");

int i = statement.executeUpdate();
if(i>0) System.out.println("插入成功");

//6.关闭连接,释放资源(一定)
statement.close();
connection.close();
posted @ 2021-10-13 19:04  OmegaGO  阅读(33)  评论(0编辑  收藏  举报