北京行——JSP入门与Servlet精通

Servlet技术 用来动态生成 网页数据资源
Servlet生成HTML 页面数据时,所有内容都是通过 response.getWriter response.getOutputStream 向浏览器输出的

<html>
<head>
</head>
<body>
Hello
</body>
</html>

用Servlet 输出流打印网页信息
response.getWriter().print("<html>");

Servlet生成网页缺点
1、通过print输出网页 开发很不方便
2、美工人员经常对页面进行CSS修饰,美工人员在java代码中调试CSS
3、无法使用开发工具对页面代码进行调试 JS CSS

98前后 主流网页设计技术 ASP PHP , sun推出Servlet,sun参考ASP语法推出JSP
* 什么是 JSP ? JSP 和Servlet技术一样,都是动态网页开发技术  Java Server Page

* JSP 和 Servlet 关系? JSP在运行时,需要先翻译为Servlet才能运行 ------ JSP 就是 Servlet ,这个工作是由编译器给搞定了 
Servlet2.5 版本 ---- JavaEE 5.0 ---- JSP 版本2.1

编写第一个JSP程序
1、JSP位于WebRoot下 --- 不能放入WEB-INF(不能访问)
2、修改JSP默认编码 window --- preferences --- JSP 修改编码 utf-8
3、修改JSP 默认编辑器 window --- preferences --- general ---- editor ---- File Associations 将 JSP编辑器改为 JSP Editor
4、在WebRoot下 新建 JSP ---- hello.jsp
5、写JSP过程和编写HTML一样,可以通过<%%> 嵌入java代码

* 有人比喻 Servlet:嵌入HTML的java文件 ; JSP :嵌入Java的HTML文件

JSP运行原理:
1、客户端访问hello.jsp
2、服务器读取hello.jsp内容到内存
3、服务器根据hello.jsp内容生成Servlet程序 ----保存在哪? tomcat/work
4、Servlet编译运行

JSP翻译Servlet 固定包名 :org.apache.jsp
hello.jsp ---- hello_jsp.java

JSP中 HTML代码 <%%> 代码都会被翻译Servlet 中 _jspService
翻译规则:
1、JSP 中 HTML 翻译 out.write
2. JSP中java代码 不会翻译

JSP中脚本元素 中都是使用%
1、声明 <%! %> --- 定义内容将会被翻译Servlet类 成员变量和方法
2、表达式 <%= %> ---- 用于向页面输出内容 等价于 out.print()
3、代码块<% %> --- 在<%%> 之间编写任何java代码
* 代码块可以和html嵌套使用

开发网页程序,使用Servlet? 使用JSP呢?
Java代码多 --- Servlet
HTML代码多 ---- JSP

JSP运行时 总要翻译Servlet ,效率很低 ?
* 只有第一次访问JSP 进行翻译 ,以后访问,如果没有修改 JSP 不会重新翻译

EL 全名为Expression Language ---- 表达式语言
语法:${标识符}
${applicationScope.name } 等价于 <%=getServletContext().getAttribute("name") %>
${requestScope.address } 等价于 <%=request.getAttribute("address") %>

JSTL (JSP Standard Taglib Liberary) --- JSP 标准标签库
JSTL干嘛用的? 简化页面<%%> 与 HTML嵌套写法 ----- 简化JSP开发

今天学习目标: <c:forEach> <c:if> ----- 用来替换页面中for循环 和 if条件判断

在页面内使用JSTL 简化 if 和 for
1、导入jstl的jar包 --- MyEclipse中存在 javaee5 类库 ---存在 jstl1.2.jar
2、在页面最上方 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
* 定义了很多标签,为标签指定名称空间 uri ,在使用标签前 引用名称空间
JSTL+EL 简化 <%%> 脚本代码

------------------------------------------------------------------------------------------------------
什么是会话? 用户打开浏览器,访问站点,连续进行多次操作,关闭浏览器 ,整个过程称为会话 。

管理HTTP协议会话状态 :Cookie 和Session
Cookie:将用户相关数据,保存客户端 , 用户每次访问服务器自动携带cookie数据 。
Session : 将用户相关数据 保存服务器端,为每个客户端生成一个独立Session数据对象,通过对象唯一编号,区分哪个浏览器对应 哪个Session

Cookie快速入门 案例:上次访问时间
1、通过服务器向客户端写cookie
Cookie cookie = new Cookie(name,value);
response.addCookie(cookie);
* 在HTTP协议响应头信息中 Set-Cookie: last=1339556457609

2、当客户端存在cookie之后,以后每次请求自动携带 HTTP协议请求头信息 Cookie: last=1339556456859
服务器端获得需要cookie数据
Cookie[] cookies = request.getCookies(); ---- 获得客户端所有cookie
if(cookies==null){} 判断cookie是否存在

遍历cookie获得需要信息
for (Cookie cookie : cookies) {
// 获得每个cookie
if (cookie.getName().equals("last")) {
// 找到了需要cookie
}
}

代码附上:

public class CookieServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        response.setContentType("text/html;charset=utf-8");
        if (cookies == null) {
            long now = System.currentTimeMillis();
            response.addCookie(new Cookie("lastTime", now + ""));
            response.getWriter().write("欢迎首次来购物!");
        } else {

            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastTime")) {
                    String lastTime = cookie.getValue();
                    System.out.println("第二次");
                    Long time = Long.parseLong(lastTime);
                    System.out.println(time);
                    Date date = new Date(time);// 没想到在这个时间上费了很大的力气
                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy年MM月dd日HH时mm分ss秒");
                    response.getWriter().write(
                            "上次访问时间是:" + dateFormat.format(date));
                }
            }
        }
        long now = System.currentTimeMillis();
        response.addCookie(new Cookie("lastTime", now + ""));
    }// 添加了这个后会更新上次的访问时间

 

 

 

CookieAPI 详解
1、将cookie写回客户端 response.addCookie(cookie);
2、读取请求中 cookie信息 request.getCookies
3、Cookie对象创建 new Cookie(name,value )
* cookie的name 不允许改变 ----- getName 、getValue 、setValue

4、什么是会话cookie ,什么是持久cookie ?
cookie信息默认情况 保存在浏览器内存中 ------ 会话cookie
会话cookie 会在关闭浏览器时 清除

持久Cookie,cookie数据保存客户端硬盘上
通过setMaxAge 设置Cookie为持久Cookie
* 在JavaAPI 中所有与时间相关参数,int 类型 单位秒, long类型 单位毫秒

5、访问cookie有效路径path
默认情况下,生成cookie时,产生默认有效访问路径 (默认生成cookie程序路径)
http://localhost/day07/lastvisit --- 生成cookie --- path 默认值: /day07
http://localhost/day07/servlet/path ---- 生成cookie ---- path 默认值:/day07/servlet

第二次访问程序携带cookie信息,如果访问路径与path不一致,不会携带cookie 信息
company cookie : path --- /day07/serlvet
last cookie : path --- /day07

访问 :http://localhost/day07/servlet/path ---- 同时满足/day07/serlvet、/day07 携带 company 和 last两个cookie信息
访问 :http://localhost/day07/lastvisit ---- 满足 /day07 不满足/day07/serlvet 携带 last 一个cookie 信息
* 以后程序开发,尽量设置path ---- setPath方法    主要是为了统一,好管理 这是我认为的  主要是为了方便管理cookie在哪里,什么时候能全部用到

6、第一方cookie 和 第三方cookie
通过setDomain 设置cookie 有效域名
访问google时,生成cookie过程中 cookie.setDomain(".baidu.com") ---- 生成百度cookie ------ 第三方cookie
* 第三方cookie 属于不安全 ----- 一般浏览器不接受第三方cookie

访问google时,生成cookie,cookie.setDomain(.google.con) ---- 生成google的cookie ------ 第一方cookie

案例:删除上次访问时间
原理:设置cookie MaxAge为 0
* 删除cookie时 必须设置path 与cookie的 path一致


案例:商品浏览记录 ---- 可以通过Cookie实现

代码附上:

Goods.jsp

<body>
<h1>请选择你想购买的商品</h1>
    <a href="/day7/BuyHistory?id=1">洗衣机</a>
    <a href="/day7/BuyHistory?id=2">冰箱</a>
    <a href="/day7/BuyHistory?id=3">茅台</a>
    <a href="/day7/BuyHistory?id=4">手机</a>
    <a href="/day7/BuyHistory?id=5">电脑</a>
    <a href="/day7/BuyHistory?id=6">电视</a>
    <br>
    <h1>你上次浏览的商品是:</h1><br>
    <a href="/day7/clearServlet">清除浏览记录</a>
    <br>
<%
    String[] goods = { "洗衣机", "冰箱", "茅台", "手机", "电脑", "电视" };
    Cookie[] cookies = request.getCookies();
    Cookie cookie = CookieUntil.findCookie(cookies,"history");
    String[] idsArr = cookie.getValue().split(",");
    for(String string :idsArr){
        out.print(goods[Integer.parseInt(string)-1]+"<br>");
    }
%>
</body>

Buyhistory.java

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String[] goods = { "洗衣机", "冰箱", "茅台", "手机", "电脑", "电视" };
        String id = request.getParameter("id");
        response.getWriter().write(
                "你现在正在访问的商品是:" + goods[Integer.parseInt(id) - 1]);
        response.getWriter().write("<a href=\"/day7/Goods.jsp\">点击返回首页</a>");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUntil.findCookie(cookies, "history");
        if (cookie == null) {
            cookie = new Cookie("history", id);
            cookie.setMaxAge(60 * 60 * 60);
            cookie.setPath("/day7");
            response.addCookie(cookie);
        } else {
            String[] idsArr = cookie.getValue().split(",");
            String str = null;
            for (String string : idsArr) {
                if (string.equals(id)) {// 比较字符串一定要用equals方法
                    return;
                } else {
                    str = cookie.getValue() + "," + id;
                }
            }
            cookie.setValue(str);
            cookie.setMaxAge(60 * 60 * 60);
            cookie.setPath("/day7");
            response.addCookie(cookie);
        }
    }

CookieUntils.java

public class CookieUntil {
    public static Cookie findCookie(Cookie[] cookies, String name) {
        if (cookies == null) {
            return null;
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}

ClearServlet.java

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cookie cookie = new Cookie("history", "");
        cookie.setMaxAge(-1);
        cookie.setPath("/day7");
        response.addCookie(cookie);
    }

 

 

-----------------------------------------------------------------------------------------------------------------------

Session 是服务器端会话管理技术,服务器会为每个浏览器创建一个单独Session对象,保存该浏览器(会话)操作相关信息。
与Cookie区别:cookie是保存在客户端,Session保存在服务器端

为什么有Cookie技术?还需要Session ?
Cookie 存在客户端 ----存在安全问题
Session将数据存在服务器,数据更加安全
* Session将数据保存在服务器端,占用服务器内存资源 ,Cookie不会占用服务器资源
例如:京东购物车信息 保存Cookie 、淘宝购物车信息保存Session

Session共享
实验:用IE6 向Session保存一个数据,用另一个IE6读取数据?

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("name", "kongbin");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("已经写入到了Session");
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(request.getSession().getAttribute("name"));
    }

 


用第一个IE6保存session数据,当前浏览器可以获得,但是第二个IE6 无法获得第一个浏览器保存Session 数据

IE8以上 或 火狐浏览器:当打开多个浏览器窗口,之间Session共享

原因:IE6 cookie 中保存jsessionId 默认会话级别 ;IE8或者火狐 保存cookie中 jsessionId 默认持久cookie

问题:如何让多个IE6 共享同一个Session ---- 将session id 持久化

问题:如果客户端关闭浏览器,是否就删除了Session ?
没有,Session保存在服务器端

问题:IE6 保存Session,关闭浏览器,再次打开,数据丢失了?
IE6默认jsessionId保存会话Cookie中,关闭浏览器,会话cookie就会被删除,客户端丢失jsessionid 无法找到服务器对应Session对象
* 服务器Session对象还存在

Cookie cookie = new Cookie("JSESSIONID", httpSession.getId());
        cookie.setMaxAge(60 * 60);
        cookie.setPath("/day7");

 

 

Session购物车案例
1、商品列表,用户点击列表中商品,将商品添加购物车
2、查看购物车中商品,以及商品购买件数

product.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>请选择你想购买的商品</h1>
    <a href="/day7/shoppingcart?id=1">洗衣机</a>
    <a href="/day7/shoppingcart?id=2">冰箱</a>
    <a href="/day7/shoppingcart?id=3">茅台</a>
    <a href="/day7/shoppingcart?id=4">手机</a>
    <a href="/day7/shoppingcart?id=5">电脑</a>
    <a href="/day7/shoppingcart?id=6">电视</a>
    <br>
    <h1>你上次浏览的商品是:</h1><br>
    <a href="/day7/clearServlet">查看购物车</a>

</body>
</html>

ShopingCart.java

package cn.binbin.com;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShoppingCart extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String[] goods = { "洗衣机", "冰箱", "茅台", "手机", "电脑", "电视" };
        String id = request.getParameter("id");
        HttpSession httpSession = request.getSession();
        Map<String, Integer> map = (Map<String, Integer>) httpSession
                .getAttribute("map");// 这个地方是个重点,这个地方用到了一个比较好的思想
        if (map == null) {
            map = new HashMap<String, Integer>();
            map.put(id, 1);
        } else {
            if (map.containsKey(id)) {// 这个地方是添加的判断
                map.put(id, map.get(id) + 1);
            } else {
                map.put(id, 1);// 第一次老是出现一件商品,这就是没有添加的缘故
            }
        }
        httpSession.setAttribute("map", map);// 忘记了写回了
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(
                "你购买的商品是:   " + goods[Integer.parseInt(id) - 1] + "    ");
        response.getWriter().write(
                "<a href = '/day7/cart.jsp'>" + "    查看购物车" + "</a>");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}

car.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%  
    String[] goods = { "洗衣机", "冰箱", "茅台", "手机", "电脑", "电视" };
    HashMap <String ,Integer> map = (HashMap<String,Integer>)request.getSession().getAttribute("map");
    for(String name :map.keySet()){
        out.print(goods[Integer.parseInt(name)-1]);
        out.println(map.get(name)+"<br>");
        
    }
    out.print("<a href='/day7/product.jsp'>"+"返回购物界面"+"</a>");
%>
</body>
</html>

 

 

禁用Cookie后,Session还能否使用?
可以,可以对url进行重写,原理在url;jsessionid=xxx ---- 在程序中可以调用response.encodeURL进行URL重写
* 如果服务器进行URL重写,所有路径都必须重写
* 不要让用户禁用cookie

Cookie生命周期
Cookie 对象何时创建,何时销毁
创建 : Cookie cookie = new Cookie(name,value) ; response.addCookie(cookie);
销毁 : 会话cookie会在浏览器关闭时销毁,持久cookie会在cookie过期(MaxAge)后销毁

Session生命周期
创建:request.getSession() 创建Session
销毁:三种 1、服务器关闭时销毁 2、session过期时销毁 3、手动调用session.invalidate

设置session过期时间
1、配置web.xml
<session-config>单位是分钟:连续30分钟不使用session
<session-timeout>30</session-timeout>
</session-config>
2、调用session对象 setMaxInactiveInterval(int interval) 单位是秒
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60*60); 设置session过期时间1小时

上述是经典面试题

 

案例:Session经常用来完成系统权限和认证功能
权限:在用户身份认证后,根据权限知道 --- 你能做什么
认证:用户登陆 --- 你是谁

将登陆用户信息保存到Session 有什么作用 ? ---- 如果session中没有用户信息 未登陆


案例:通过session实现一次性验证码
* 验证码从session获取后,马上删除 ---- 验证码只能使用一次

CheckImg.java

package cn.binbin.com;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckImg extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1、在内存中缓冲一张图片
        int width = 120;
        int height = 30;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        // 2、设置背景色
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.YELLOW);
        graphics.fillRect(0, 0, width, height);
        // 3、画边框
        graphics.setColor(Color.BLUE);
        graphics.drawRect(0, 0, width - 1, height - 1);
        // 5、开始找字库了
        String content = "ASDFGHJKJKLQWERTYUIOZXCVBNM1234567890";
        // 6、设置字体
        graphics.setFont(new Font("宋体", Font.BOLD, 20));
        // 如果验证码是中文,必须用中文的字库
        Random random = new Random();
        int x = 10;
        int y = 20;
        StringBuffer str = new StringBuffer("");
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(content.length());
            char c = content.charAt(index);
            str.append(c);
            double angle = random.nextInt(60) - 30;// 这个地方是因为randomo不能生产负数
            double theta = angle / 180 * Math.PI;
            graphics.rotate(theta, x, y);
            graphics.drawString(c + "", x, y);
            graphics.rotate(-theta, x, y);
            x += 20;
        }
        String checkImg = str.toString();
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("checkImg", checkImg);
        // 7、绘制干扰线
        int x1, x2, y1, y2;
        graphics.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 10; i++) {
            x1 = random.nextInt(width);
            x2 = random.nextInt(width);
            y1 = random.nextInt(height);
            y2 = random.nextInt(height);
            graphics.drawLine(x1, y1, x2, y2);

        }

        // 7、添加旋转,用的是graphic2D来画

        // 4、把内存中的图片输出到浏览器
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function change(){
        document.getElementById("img").src="/day7/CheckImg";
        }
</script>
</head>
<body>
<h2 style="color: red">${requestScope.msg}</h2>
<form action="/day7/LoginServlet">
    姓名:<input type="text" name="username">
    密码:<input type="password" name = "password">
    验证码:<input type="text" name = "checkimg"><img src="/day7/CheckImg" onclick="change()"id = "img" style="cursor: pointer">
    <input type="submit" value="提交"> 
</form>
</body>
</html>

LoginServlet.java

package cn.binbin.com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession httpSession = request.getSession();
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String checkImg = request.getParameter("checkimg");
        String checkImg2 = (String) httpSession.getAttribute("checkImg");
        httpSession.removeAttribute("checkImg");// 这个地方的销毁是为了进行一次验证
        // 这个地方验证是有先后顺序的
        if (checkImg.equals(checkImg2)) {
            if (name.equals("kongbin") && password.equals("kongbin")) {
                httpSession.setAttribute("name", name);
                response.sendRedirect("/day7/welcome.jsp");
            } else {
                request.setAttribute("msg", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,
                        response);
            }
        } else {
            request.setAttribute("msg", "验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,
                    response);
        }
        // if ((name.equals("kongbin") && password.equals("kongbin"))
        // && (checkImg.equals(checkImg2))) {
        // httpSession.setAttribute("name", name);
        // response.sendRedirect("/day7/welcome.jsp");
        // } else {
        // response.sendRedirect("/day7/login.jsp");
        // }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

}

Welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>欢迎回来<%=request.getSession().getAttribute("name") %></h1>
</body>
</html>

 

 

---------------------------------------------------------------------------------------
Servlet 三种数据范围
ServletContext
HttpServletRequest
HttpSession

三种数据范围,每个对象各自维护类似map集合结构,具备相同几个方法
setAttribute 存入一个属性
getAttribute 取出一个属性
removeAttribute 移除一个属性

三种数据范围对象 在哪些情况使用?
ServletContext 服务器启动时创建,服务器关闭销毁 所有Servlet共享 ---- 保存一些全局数据
例如:数据库连接池、工程配置属性、配置文件内容 ----- 一般不建议使用,服务器占用内存过多

HttpSession 在request.getSession时创建,在三种情况下销毁 ----- 保存与用户相关数据
例如:系统登陆信息、购物车数据

HttpServletRequest 在客户端发起请求时,服务器创建对象,在响应结束时 对象销毁 ----- 保存Servlet向JSP传输数据信息
例如:执行某个操作,Servlet将操作结果传递JSP (Servlet将登陆错误信息传递JSP )、Servlet将数据库查询结果传递JSP

用request的时候是比较多的

 

以上三种数据范围 ServletContext > HttpSession > HttpServletRequest
* 宗旨 优先使用生命周期短的,降低服务器的压力


总结 :
day5
1、编写一个Servlet --- HelloWorld response.getWriter().print()
2、设置response编码集,向浏览器输入中文信息 response.setContentType("text/html;charset=utf-8");
3、将九九乘法表打印浏览器页面 ----- 添加for循环
4、编写页面让用户输入一个数字,在Servlet根据用户输入数字 打印乘法表
5、用户输入一段字母内容,在浏览器上输入 每个字符出现几次
6、网站访问次数 (选做)
7、读取web工程中一个文件 (getServletContext().getRealPath())


理论:
1、Servlet生命周期
2、ServletConfig和ServletContext
3、url-pattern 三种写法

day6
1、重定向 ---- response.setStatus response.setHeader
2、自动跳转 ---- refresh
3、禁用缓存 ---- 三个头信息
4、文件下载 (复杂值得做)
5、验证码程序 整理一下 (不用重写)
6、获得当前访问资源路径 request.getRequestURI().substring(request.getContextPath().length());
7、获得客户端 IP request.getRemoteAddr()
8、防盗链 request.getHeader(referer)
9、获得请求参数 乱码问题 post get 乱码解决 (昨天重点**** )

理论:
1、200、302 、304 、404 、500 意思
2、refrer refresh Content-Type Content-Disposition 禁止缓存三个头 ----- 含义
3、get和post请求方式区别
4、乱码发生原因 (掌握)

day7
1、记录上次访问时间 cookie
2、商品浏览记录 cookie
3、商品购物车 session
4、登陆一次性验证码 session

理论:
1、cookie和session区别
2、会话cookie 和持久cookie
3、第一方cookie和第三方cookie
4、关闭浏览器是否清除cookie ?
5、持久cookie删除
6、关闭浏览器,重新打开浏览器session还能继续使用 ?原理 ?
7、浏览器禁用cookie,session还能否使用
8、session销毁三种情况
9、一次性验证码原理
10、Servlet三种数据范围区别

posted @ 2013-04-19 17:42  蓝冰悠见  阅读(250)  评论(0编辑  收藏  举报