/*
之前的写法
response.setStatus(302);
response.setHeader("Location", "login_success.html");*/
//重定向写法: 重新定位方向 参数即跳转的位置
response.sendRedirect("login_success.html");
//请求转发的写法: 参数即跳转的位置
request.getRequestDispatcher("login_success.html").forward(request, response);
饼干。其实是一份小数据, 是服务器给客户端,并且存储在客户端上的一份小数据
自动登录、浏览记录、购物车。
http的请求是无状态。 客户端与服务器在通讯的时候,是无状态的,其实就是客户端在第二次来访的时候,服务器根本就不知道这个客户端以前有没有来访问过。 为了更好的用户体验,更好的交互 [自动登录],其实从公司层面讲,就是为了更好的收集用户习惯[大数据]
在响应的时候,添加cookie
Cookie cookie = new Cookie("aa", "bb");
//给响应,添加一个cookie
response.addCookie(cookie);
客户端收到的信息里面,响应头中多了一个字段 Set-Cookie
//获取客户端带过来的cookie
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie c : cookies) {
String cookieName = c.getName();
String cookieValue = c.getValue();
System.out.println(cookieName + " = "+ cookieValue);
}
}
//关闭浏览器后,cookie就没有了。 ---> 针对没有设置cookie的有效期。
// expiry: 有效 以秒计算。
//正值 : 表示 在这个数字过后,cookie将会失效。
//负值: 关闭浏览器,那么cookie就失效, 默认值是 -1
cookie.setMaxAge(60 * 60 * 24 * 7);
//赋值新的值
//cookie.setValue(newValue);
//用于指定只有请求了指定的域名,才会带上该cookie
cookie.setDomain(".itheima.com");
//只有访问该域名下的cookieDemo的这个路径地址才会带cookie
cookie.setPath("/CookieDemo");
判断账号是否正确
如果正确,则获取cookie。 但是得到的cookie是一个数组, 我们要从数组里面找到我们想要的对象。
如果找到的对象为空,表明是第一次登录。那么要添加cookie
如果找到的对象不为空, 表明不是第一次登录。
if("admin".equals(userName) && "123".equals(password)){
//获取cookie last-name --- >
Cookie [] cookies = request.getCookies();
//从数组里面找出我们想要的cookie
Cookie cookie = CookieUtil.findCookie(cookies, "last");
//是第一次登录,没有cookie
if(cookie == null){
Cookie c = new Cookie("last", System.currentTimeMillis()+"");
c.setMaxAge(60*60); //一个小时
response.addCookie(c);
response.getWriter().write("欢迎您, "+userName);
}else{
//1. 去以前的cookie第二次登录,有cookie
long lastVisitTime = Long.parseLong(cookie.getValue());
//2. 输出到界面,
response.getWriter().write("欢迎您, "+userName +",上次来访时间是:"+new Date(lastVisitTime));
//3. 重置登录的时间
cookie.setValue(System.currentTimeMillis()+"");
response.addCookie(cookie);
}
}else{
response.getWriter().write("登陆失败 ");
}
拷贝基础课第一天的 htmll原型文件,到工程的WebContent里面。
在WebContent目录下新建一个jsp文件, product_list.jsp, 然后拷贝原来product_list.html的内容到jsp里面。 建好之后,jsp里面的所有ISO-8859-1 改成 UTF-8。拷贝html标签的所有内容。 替换jsp的html标签即可
修改product_info.htm里面的手机数码超链接地址
<li class="active"><a href="product_list.jsp">手机数码<span class="sr-only">(current)</span></a></li>
修改首页(index.html)顶部的手机数码跳转的位置为 product_list.jsp
<li class="active"><a href="product_list.jsp">手机数码<span class="sr-only">(current)</span></a></li>
Jsp 里面使用Java代码
Java Server Pager ---> 最终会翻译成一个类, 就是一个Servlet
- 定义全局变量
<%! int a = 99; %>- 定义局部变量
<% int b = 999; %>- 在jsp页面上,显示 a 和 b的值,
<%=a %>
<%=b %>
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// System.out.println("--------------1-----------");
// 获取当先用户准备浏览的id
String id = request.getParameter("id");
Cookie[] cookies = request.getCookies();
Cookie cookie = CookieUtil.findCookie(cookies, "history");
// 第一次浏览
if (cookie == null) {
// 1.响应返回cookie
Cookie c = new Cookie("history", id);
//设置有效期
c.setMaxAge(60*60*24*7);
//设置访问这个项目的时候,才带cookie过来
c.setPath("/CookieDemo");
response.addCookie(c);
}else {
//第二次
//1.获取以前的cookie,以前的cookie包含浏览记录
String ids = cookie.getValue();
//2.让现在浏览的商品,和以前浏览的商品,影响cookie新的值
cookie.setValue(id+"#"+ids);
response.addCookie(cookie);
//设置有效期
cookie.setMaxAge(60*60*24*7);
//设置访问这个项目的时候,才带cookie过来
cookie.setPath("/CookieDemo");
}
//跳转
response.sendRedirect("product_info.htm");
}
其实就是清除Cookie, 删除cookie是没有什么delete方法的。只有设置maxAge 为0 。
Cookie cookie = new Cookie("history","");
cookie.setMaxAge(0); //设置立即删除
cookie.setPath("/CookieDemo");
response.addCookie(cookie);
会话 , Session是基于Cookie的一种会话机制。 Cookie是服务器返回一小份数据给客户端,并且存放在客户端上。 Session是,数据存放在服务器端。
常用API
//得到会话ID
String id = session.getId();
//存值
session.setAttribute(name, value);
//取值
session.getAttribute(name);
//移除值
session.removeAttribute(name);
创建
如果有在servlet里面调用了 request.getSession()
销毁
session 是存放在服务器的内存中的一份数据。 当然可以持久化. Redis . 即使关了浏览器,session也不会销毁。
response.setContentType("text/html;charset=utf-8");
//1. 获取要添加到购物车的商品id
int id = Integer.parseInt(request.getParameter("id")); // 0 - 1- 2 -3 -4
String [] names = {"Iphone7","小米6","三星Note8","魅族7" , "华为9"};
//取到id对应的商品名称
String name = names[id];
//2. 获取购物车存放东西的session Map<String , Integer> iphoen7 3
//把一个map对象存放到session里面去,并且保证只存一次。
Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");
//session里面没有存放过任何东西。
if(map == null){
map = new LinkedHashMap<String , Integer>();
request.getSession().setAttribute("cart", map);
}
//3. 判断购物车里面有没有该商品
if(map.containsKey(name)){
//在原来的值基础上 + 1
map.put(name, map.get(name) + 1 );
}else{
//没有购买过该商品,当前数量为1 。
map.put(name, 1);
}
//4. 输出界面。(跳转)
response.getWriter().write("<a href=‘product_list.jsp‘><h3>继续购物</h3></a><br>");
response.getWriter().write("<a href=‘cart.jsp‘><h3>去购物车结算</h3></a>");
//强制干掉会话,里面存放的任何数据就都没有了。
session.invalidate();
//从session中移除某一个数据
//session.removeAttribute("cart");
请求转发和重定向(面试经常问)
Cookie
服务器给客户端发送一小份数据, 存放在客户端上。
基本用法:
添加cookie
获取cookie
演练例子:
1. 获取上一次访问时间
2. 获取商品浏览记录
什么时候有cookie
response.addCookie(new Cookie())
会话Cookie:关闭浏览器,就失效
持久Cookie:存放在客户端上。 在指定的期限内有效。setMaxAge();
也是基于cookie的一种会话技术, 数据存放存放在服务器端
会在cookie里面添加一个字段 JSESSIONID . 是tomcat服务器生成。
setAttribute 存数据
getAttribute 取数据
removeAttribute 移除数据
getSessionId(); 获取会话id
invalidate() 强制让会话失效。
创建:调用request.getSesion创建
销毁:服务器关闭 , 会话超时(30分)
setAttribute 存放的值, 在浏览器关闭后,还有没有。 有!,就算客户端把电脑砸了也还有。
【从零开始学Servlet笔记】Cookie&Session
原文:https://www.cnblogs.com/zllk/p/12821786.html