JSPday03(application、四大作用域、cookie)
Application
application的生命周期非常长,与服务器的生命周期相同,一般会放在存储时间较长的需求当中。
api网址:https://tool.oschina.net/apidocs
四大作用域
page作用域:pageContext
request作用域:request
session作用域:ression
application作用域:application
Cookie
Cookie是web服务器保存在客户端中的一系列文本信息,由于是文本类型存储,所以安全性极差,不适合放置一些特别重要或安全敏感信息。
cookie的使用
创建cookie:
创建cookie:
写出cookie:
读取cookie:
由于在一个域(domain)下,会存储多个cookie值,那么读取时,获取到的实际上是一个cookie数组。
利用cookie实现7天内免登录
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <% 3 //处理乱码 4 request.setCharacterEncoding("UTF-8"); 5 response.setCharacterEncoding("UTF-8"); 6 7 //获取用户名密码 8 String username = request.getParameter("uname") ; 9 String password = request.getParameter("upass") ; 10 String rent_login = null ; 11 if(request.getParameterValues("rent_login") != null) { 12 rent_login = request.getParameterValues("rent_login")[0] ; 13 } 14 15 16 //判断用户名密码 17 if("admin".equals(username) && "123456".equals(password)) { 18 //创建session 19 session.setAttribute("username",username); 20 21 if("true".equals(rent_login)) { 22 //将用户信息写入到cookie 23 Cookie cookie = new Cookie("username",username) ; 24 25 cookie.setPath("/"); 26 //设置7天免登录 27 cookie.setMaxAge(60*60*24*7); 28 29 response.addCookie(cookie); 30 31 } 32 33 request.getRequestDispatcher("index.jsp").forward(request,response); 34 35 36 } 37 %> 38 39 读取cookie: 40 <% 41 //读取cookie 42 Cookie[] cookies = request.getCookies() ; 43 44 if(cookies != null) { 45 //判断是否有cookie名称为username 46 for(Cookie cookie : cookies) { 47 if("username".equals(cookie.getName())) { 48 session.setAttribute("username",cookie.getValue()); 49 } 50 } 51 52 } 53 String username = (String) session.getAttribute("username"); 54 55 if(username != null) { 56 out.print("您好," + username); 57 }else{ 58 response.sendRedirect("form.html"); 59 } 60 %>
session和cookie的区别: