Servlet(二)学习笔记(重定向、请求转发、Cookie、Session)

Servlet(二)

Servlet+JDBC应用

在这里插入图片描述

重定向和转发

重定向的概述

首先客户浏览器发送http请求,当web服务器接受后发送302状态码响应及对应新的location给客户浏览器,客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址,服务器根据此请求寻找资源并发送给客户。

实现重定向需要借助javax.servlet.http.HttpServletResponse接口中的方法

void sendRedirect(String location) 使用指定的重定向位置URL向客户端发送临时重定向响应

在这里插入图片描述

重定向的特点

重定向之后,浏览器地址栏的URL会发生改变。
重定向过程中会将前面Request对象销毁,然后创建一个新的Request对象。
重定向的URL可以是其它项目工程。

转发的概述

转发的概念

一个Web组件(Servlet/JSP)将未完成的处理通过容器转交给另外一个Web组件继续处理,转发的各个组件会共享Request和Response对象。

绑定数据到Request对象

Object getAttribute(String name) 将指定属性值作为对象返回,若给定名称属性不存在,则返回空值
void setAttribute(String name,Object o) 在此请求中存储属性值

获取转发器对象

RequestDispatcher getRequestDispatcher(String path) 返回一个RequestDispatcher对象,该对象充当位于给定路径上的资源的包装器

转发操作

void forward(ServletRequest request, ServletResponse response) 将请求从一个servlet转发到服务器上的另一个资源(Servlet、JSP文件或HTML文件)

转发的特点

转发之后浏览器地址栏的URL不会发生改变。
转发过程中共享Request对象。
转发的URL不可以是其它项目工程。

Servlet线程安全

服务器在收到请求之后,会启动一个线程来进行相应的请求处理。
默认情况下,服务器为每个Servlet只创建一个对象实例。当多个请求访问同一个Servlet时,会有多个线程访问同一个Servlet对象,此时就可能发生线程安全问题。
多线程并发逻辑,需要使用synchronized对代码加锁处理,但尽量避免使用。

@WebServlet(name = "ThreadServlet",urlPatterns = "/thread")
public class ThreadServlet extends HttpServlet {
    private String name;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        synchronized (this) {
            name = request.getParameter("name");
            System.out.println(name);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            PrintWriter writer = response.getWriter();
            writer.write("<h1>" + name + "</h1>");
            writer.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

状态管理

Web程序基于HTTP协议通信,而HTTP协议是”无状态”的协议,一旦服务器响应完客户的请求之后,就断开连接,而同一个客户的下一次请求又会重新建立网络连接。
服务器程序有时是需要判断是否为同一个客户发出的请求,比如客户的多次选购商品。因此,有必要跟踪同一个客户发出的一系列请求。
把浏览器与服务器之间多次交互作为一个整体,将多次交互所涉及的数据保存下来,即状态管理。
多次交互的数据状态可以在客户端保存,也可以在服务器端保存。状态管理主要分为以下两类:

​ 客户端管理:将状态保存在客户端。基于Cookie技术实现。
​ 服务器管理:将状态保存在服务器端。基于Session技术实现。

Cookie技术

Cookie本意为”饼干“的含义,在这里表示客户端以“名-值”形式进行保存的一种技术。
浏览器向服务器发送请求时,服务器将数据以Set-Cookie消息头的方式响应给浏览器,然后浏览器会将这些数据以文本文件的方式保存起来。
当浏览器再次访问服务器时,会将这些数据以Cookie消息头的方式发送给服务器。

使用javax.servlet.http.Cookie类的构造方法实现Cookie的创建。

Cookie(String name, String value) 根据参数指定数值构造对象

使用javax.servlet.http.HttpServletResponse接口的成员方法实现Cookie的添加。

void addCookie(Cookie cookie) 添加参数指定的对象到响应

使用javax.servlet.http.HttpServletRequest接口的成员方法实现Cookie对象的获取。

Cookie[] getCookies() 返回此请求中包含的所有Cookie对象

使用javax.servlet.http.Cookie类的构造方法实现Cookie对象中属性的获取和修改。

String getName() 返回此Cookie对象中的名字
String getValue() 返回此Cookie对象的数值
void setValue(String newValue) 设置Cookie的数值

@WebServlet(name = "CookieServlet",urlPatterns = "/cookie")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("测试!!");
        Cookie cookie = new Cookie("name","zhangfei");
        response.addCookie(cookie);
        System.out.println("添加cookie");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
@WebServlet(name = "Cookie2Servlet",urlPatterns = "/cookie2")
public class Cookie2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        System.out.println("获取到的Cookie信息有:");
        for (Cookie cookie : cookies){
            System.out.println(cookie.getName() + "对应的值为:" + cookie.getValue());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
@WebServlet(name = "Cookie3Servlet",urlPatterns = "/cookie3")
public class Cookie3Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if ("name".equalsIgnoreCase(cookie.getName())){
                cookie.setValue("guanyu");
                response.addCookie(cookie);
                break;
            }
        }
        System.out.println("修改Cookie信息成功!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Cookie的生命周期

默认情况下,浏览器会将Cookie信息保存在内存中,只要浏览器关闭,Cookie信息就会消失。

如果希望关闭浏览器后Cookie信息仍有效,可以通过Cookie类的成员方法实现。

int getMaxAge() 返回cookie的最长使用期限(以秒为单位)
void setMaxAge(int expiry) 设置cookie的最长保留时间(秒)

@WebServlet(name = "Cookie4Servlet",urlPatterns = "/cookie4")
public class Cookie4Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("name","liubei");
        int maxAge = cookie.getMaxAge();
        System.out.println(maxAge);
        cookie.setMaxAge(0);    //正数表示指定秒数后失效   负数表示浏览器关闭后失效    0代表马上失效
        response.addCookie(cookie);
        System.out.println("!!!!!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Cookie的路径问题

浏览器在访问服务器时,会比较Cookie的路径与请求路径是否匹配,只有匹配的Cookie才会发送给服务器。

Cookie的默认路径等于添加这个Cookie信息时的组件路径,例如:/项目名/目录/add.do请求添加了一个Cookie信息,则该Cookie的路径是 /项目名/目录。

访问的请求地址必须符合Cookie的路径或者其子路径时,浏览器才会发送Cookie信息。

void setPath(String uri) 设置cookie的路径信息

@WebServlet(name = "Cookie5Servlet",urlPatterns = "/cookie5")
public class Cookie5Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = new Cookie("name","huangzhong");
        cookie.setPath(request.getContextPath() + "/hello");
        response.addCookie(cookie);
        System.out.println("设置成功!");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Cookie的特点

Cookie技术不适合存储所有数据,程序员只用于存储少量、非敏感信息

​ 将状态数据保存在浏览器端,不安全。
​ 保存数据量有限制,大约4KB左右。
​ 只能保存字符串信息。
​ 可以通过浏览器设置为禁止使用。

Session技术

Session本意为"会话"的含义,是用来维护一个客户端和服务器关联的一种技术。
浏览器访问服务器时,服务器会为每一个浏览器都在服务器端的内存中分配一个空间,用于创建一个Session对象,该对象有一个id属性且该值唯一,我们称为SessionId,并且服务器会将这个SessionId以Cookie方式发送给浏览器存储。
浏览器再次访问服务器时会将SessionId发送给服务器,服务器可以依据SessionId查找相对应的Session对象

使用javax.servlet.http.HttpServletRequest接口的成员方法实现Session的获取。

HttpSession getSession() 返回此请求关联的当前Session,若此请求没有则创建一个

使用javax.servlet.http.HttpSession接口的成员方法实现判断和获取。

boolean isNew() 判断是否为新创建的Session
String getId() 获取Session的编号

使用javax.servlet.http.HttpSession接口的成员方法实现属性的管理。

Object getAttribute(String name) 返回在此会话中用指定名称绑定的对象,如果没有对象在该名称下绑定,则返回空值
void setAttribute(String name, Object value) 使用指定的名称将对象绑定到此会话
void removeAttribute(String name) 从此会话中删除与指定名称绑定的对象

@WebServlet(name = "SessionServlet",urlPatterns = "/session")
public class SessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println(session.isNew()?"新创建Session对象":"已有的Session对象");
        System.out.println("Session的编号d为:" + session.getId());;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
@WebServlet(name = "SessionServlet2",urlPatterns = "/session2")
public class SessionServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Session的编号d为:" + session.getId());
        session.setAttribute("name","zhaoyun");
        System.out.println("获取到的属性值为:" + session.getAttribute("name"));
        session.removeAttribute("name");
        System.out.println("获取到的属性值为:" + session.getAttribute("name"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Session的生命周期

为了节省服务器内存空间资源,服务器会将空闲时间过长的Session对象自动清除掉,服务器默认的超时限制一般是30分钟。
使用javax.servlet.http.HttpSession接口的成员方法实现失效实现的获取和设置。

int getMaxInactiveInterval() 获取失效时间
void setMaxInactiveInterval(int interval) 设置失效时间

@WebServlet(name = "SessionServlet3",urlPatterns = "/session3")
public class SessionServlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println("Session的默认失效时间为:" + session.getMaxInactiveInterval());
        session.setMaxInactiveInterval(1200);
        System.out.println("Session设置的失效时间为:" + session.getMaxInactiveInterval());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

可以配置web.xml文件修改失效时间。

<session-config>
	<session-timeout>30</session-timeout>
</session-config>

Session的特点

数据比较安全。
能够保存的数据类型丰富,而Cookie只能保存字符串。
能够保存更多的数据,而Cookie大约保存4KB。
数据保存在服务器端会占用服务器的内存空间,如果存储信息过多、用户量过大,会严重影响服务器的性能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值