1.会话技术
就是浏览器和服务器的多次请求和响应
打开浏览器------>>访问------->>关闭 称之为一次会话
2.Cookie
是什么?
就是一个普通类
是客户端的会话管理技术
每次请求时,把会话信息带到服务器,从而实现多次请求的数据共享
作用:
客户端访问浏览器相关内容,保证每次从本地缓存取,提高效率
属性:
name cookie名称
Value cookie的值(不支持中文)
Path cookie路径
Domain cookie的域名
maxAge cookid存活时间
方法;
Cookie(String name,String value) 构造方法
属性对应的get和set方法 赋值和获取值
添加和获取:
添加: HTTPServletResponse
方法名 addCookie() 向客户端添加cookie 返回值为void
获取: HTTPServletRequest
方法名 getCookie() 获取所有cookie 返回值为cookie[]
Cookie使用细节
每个网站最多有20个cookie,大小不能超过4kb,所有网站不能超过300个
名称不能有字母,数字字符,逗号,分号,空格和$,不支持中文
存活时间限制 负整数: 当前会话有效
0: 立即清除
以秒为单位设置存活时间
访问路径限制
取自第一访问的资源路径前缀,只要以这个路径开头就能访问到,
设置路径:setPath()方法设置指定路径
3.Session
HTTPSession
服务端的会话技术
本质也采用客户端会话技术,是基于Cookie的
常用方法:
Getid() 获取唯一标识名称
Invalidate() 让session立即失效
基本使用:
getSession() 获取HTTPSession对象
getSession(boolean create) 获取HTTPSession对象,未获取到是否自动
4.Cookie和Session原理分析
(1)Cookie:当客户端发送一个请求,不会携带cookie,请求到达服务器,服务器可以给客户端设置一个Cookie,而共享数据保存在客户端,当下次再发请求会携带服务端设置给客户端的cookie
图解:
(2)Session:是基于Cookie的,会在客户端保存一个JSESSIONID特殊标识,而共享数据保存在服务器内存对象中,每次请求会将特殊标识带到服务器端,根据这个特殊标识,来找到内存空间,从而实现数据共享
图解:
5.Cookie和Session的区别
Session是基于Cookie的
Cookie可以理解为小甜点,它是在客户端保存共享数据的,保存共享的是不重要数据
Session可以理解为正餐,它是在服务器端保存共享数据的,保存共享重要数据
Cookie代码:
@WebServlet("/Cookie_Text")
public class Cookie_Text extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应乱码
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw = resp.getWriter();
//获取所有Cookie
Cookie[] cookies = req.getCookies();
boolean isIFrst = true;
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if ("lastTime".equalsIgnoreCase(cookie.getName())) {
//获取Cookie中为key为"lastTime"对应的value
String value = cookie.getValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(new Date(Long.parseLong(value)));
pw.write("欢迎访问本网站,您的最后访问时间为:
");
pw.write(format);
isIFrst = false;
}
}
}
if (isIFrst) {
pw.write("欢迎访问本网站...");
}
//创建cookie对象,记录最后访问时间
Cookie cookie = new Cookie("lastTime", System.currentTimeMillis() + "");
//设置最大存活时间最大为秒
cookie.setMaxAge(30);
//响应cookie
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
第一次请求服务器不会携带cookie,第二次请求会有Cookie
Session代码:
@WebServlet("/SessionDemo01")
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求用户名
String username = req.getParameter("username");
//获取Session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
//将用户名添加到session
session.setAttribute("username",username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
@WebServlet("/SessionDemo01bak")
public class SessionDemo01bak extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
//获取共享数据
Object username = session.getAttribute("username");
resp.getWriter().write("username:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
Demo01发起请求拿到username,并设置在Session域中,当Demo01bak发起请求时,会拿JSESSIONID特殊标识,去服务器端找到内存空间,从而拿到共享数据
6.HTTPSession的钝化和活化
钝化:在服务器正常关闭之前,将session对象系列化到硬盘上
活化:在服务器启动后,将session文件转化为内存中的session对象即可。
7.JSP动态网页技术标准(了解就行,企业级开发不用)
是一个特殊的Servlet,展示动态数据
执行流程分析如图:
基本语法:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>JSP基本语法</title>
</head>
<body>
<%--JSP注释--%>
<!--HTML注释-->
<%--java代码块--%>
<%
out.println("这是java代码块
");
System.out.println("java控制台输出");
%>
<%--java表达式--%>
<%="这是JSP表达式"%>
<hr/>
<%--定义全局变量--%>
<%! String name = "张三";
static int num = 20;
public static void getNum(){
}
%>
<% name = "李四";%>
<%=name%>
<%=num%>>
</body>
</html>
JSP的九大隐式对象
其中pageContext对象是jsp独有的对象,本身也是一个域对象,它还可以操作其他三个域对象的属性,还可以获取其他八个隐式对象,
声明周期:是一个局部变量,会随着JSP创建诞生,随着JSP消失而消失,每一个页面都有一个pageContext
8.四大域对象
(1)PageContext 页面范围的 最小只能在当前页面用
(2)ServletRequest 请求范围的 一次请求或当期请求转发用
(3)HTTPSession 会话范围 多次请求数据共享用
(4)ServletContext 应用范围 最大,整个应用都可以使用
四大域范围排序 (4)-------->>(3)--------->>(2)--------->>(1)
9.MVC模型
M:封装数据,数据模型
V:展示数据,动态JSP静态HTML页面
C:处理请求响应
浏览器-------发起请求----->>Servlet-----------处理请求,(转发,重定向)最后响应-------->>JSP------------处理好结果--------->>展示浏览器
10.结合以上知识 综合案例
流程分析:
index.jsp(用JSP技术判断域中有无用户登录信息,有可以跳转首页,没有,跳转登录页面)------------------->>login.jsp(登录表单,提交到Servlet功能类)----------->>LoginStudentServlet(没登录,重定向到登录页面,登录将用户信息保存在Session域中,并在indx.jsp中做判断)----------->>已登录(可选择添加和查看学生超链接)--------->>AddStudentServlet添加学生(跳转功能类)--------->>获取数据,保存到本地文件--------->>响应跳转到首页------->>ListStudentServlet查看学生(跳转功能类)------->>读取本地文件中的数据,封装对象,添加到集合中,再将集合对象设置在Session域中------------listStudent.jsp(重定向到JSP前端页面)---------->>从域中拿数据,解析,展示给客户端浏览器
代码如下:
(1)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/2/1
Time: 22:05
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学生信息管理</title>
</head>
<body>
<% Object username = session.getAttribute("username");
if (username == null) {
%>
<a href="<%pageContext.getServletContext();%>/qqq/login.jsp">请登录</a>
<%} else {
%>
<a href="<%pageContext.getServletContext().getContextPath();%>/qqq/addStudent.jsp">添加学生</a>
<a href="<%pageContext.getServletContext().getContextPath();%>/qqq/listStudent">查看学生</a>
<%}%>
</body>
</html>
(2)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/2/1
Time: 22:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>学生登录</title>
</head>
<body>
<form action="/qqq/loginStudentServlet" method="post" autocomplete="off">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<button type="submit">登录</button>
</form>
</body>
</html>
(3)
@WebServlet("/loginStudentServlet")
public class LoginStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//判断用户名是否为空
if(username==null||"".equals(username)){
//为空 重定向到登录页面
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}else {
//不为空,将数据保存到会话域中
req.getSession().setAttribute("username",username);
}
//重定向到首页
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
(4)第二段代码
(5)添加学生
@WebServlet("/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取参数信息
String username = req.getParameter("username");
String age = req.getParameter("age");
String score = req.getParameter("score");
//创建学生对象并赋值
Student stu = new Student();
stu.setUsername(username);
stu.setAge(Integer.parseInt(age));
stu.setScore(Integer.parseInt(score));
//将学生对象保存到d:\\stu.txt文件中
BufferedWriter bw = new BufferedWriter(new FileWriter("d:\\stu.txt", true));
//通过定时刷新响应给浏览器
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("添加成功,两秒后跳转首页...");
resp.setHeader("Refresh","2;URL=/qqq/index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
(6)查看学生
@WebServlet("/listStudent")
public class ListStudent extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//关联要读取的文件
BufferedReader br = new BufferedReader(new FileReader("d:\\stu.txt"));
//创建集合对象保存Studnet对象
ArrayList<Student> list = new ArrayList<>();
//循环读取文件中的数据,将数据封装到Student对象中,再把多个学生对象添加到集合中
String line;
while ((line = br.readLine()) != null) {
Student stu = new Student();
String[] arr = line.split(",");
stu.setUsername(arr[0]);
stu.setAge(Integer.parseInt(arr[1]));
stu.setScore(Integer.parseInt(arr[2]));
list.add(stu);
}
//将集合对象保存到会话域中
req.getSession().setAttribute("students",list);
//重定向到学生列表页面
resp.sendRedirect(req.getContextPath()+"/listStudent.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(7)
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.itheima.bean.Student" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/2/1
Time: 23:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>查看学生</title>
</head>
<body>
<table width="600px" border="1px">
<tr>
<th>学生姓名</th>
<th>学生年龄</th>
<th>学生成绩</th>
</tr>
<% ArrayList<Student> students = (ArrayList<Student>) session.getAttribute("students");
for (Student student : students) {
%>
<tr align="center">
<td><%=student.getUsername()%>
</td>
<td><%=student.getAge()%>
</td>
<td><%=student.getScore()%>
</td>
</tr>
<%}%>
</table>
</body>
</html>