一. 什么是会话

  1. 用户开一个浏览器,访问某一个web站点,在这个站点点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一次会话。
  2. 客户端与服务端的多次请求和响应的一个过程称之为一次会话,一次会话可以有多次请求。

二. Cookie使用

img

image-20220817185832780

  1. 创建cookie

    1
    2
    3
    4
    5
    6
    7
    8
    @RequestMapping("/add-cookie")
    @ResponseBody
    public void addCookie(HttpServletResponse resp) {
    //创建cookie对象
    final Cookie cookie = new Cookie("name", "coderyeah");
    //响应给客户端浏览器
    resp.addCookie(cookie);
    }
  2. 获取cookie

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @RequestMapping("/get-cookie")
    @ResponseBody
    public void getCookie(HttpServletRequest req) throws UnsupportedEncodingException {
    //获取所有cookie数组
    final Cookie[] cookies = req.getCookies();
    for (Cookie cookie : cookies) {
    //解码 对于中文需要编码和解码
    System.out.println(cookie.getName() + " : " + URLDecoder.decode(cookie.getValue(), "UTF-8"));//解码
    }
    }
  3. 修改cookie

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @RequestMapping(value = "/modify-cookie", produces = "application/json;charset=utf-8")
    @ResponseBody
    public void modifyCookie(HttpServletResponse resp) throws UnsupportedEncodingException {
    //因为K-V键唯一可以通过覆盖的方式修改cookie
    //编码
    final String encode = URLEncoder.encode("喜羊羊", "UTF-8");
    final Cookie cookie = new Cookie("name", encode);
    //设置cookie有效期 单位秒
    //1.正数:代表多少秒
    //2.0:就代表删除
    //3.负数:关闭浏览器时cookie失效
    cookie.setMaxAge(60 * 60 * 24 * 7);//一周
    //设置cookie作用域
    cookie.setPath("/");//根目录 整个服务器起作用
    resp.addCookie(cookie);
    }
  4. 删除cookie

    1
    cookie.setMaxAge(0);

三. cookie优缺点

  1. 缺点:
    • 不安全,cookie存在客户端;
    • 操作中文麻烦,需要编码和解码;
    • cookie不能操作对象,只能操作字符串;
    • cookie大小限制在4kb之内;
    • 一台服务器在一个客户端最多保存20个Cookie;
    • 一个浏览器最多可以保存300个Cookie。
  2. 优点:
    • 提升用户体验感;
    • 可以设置保存很长的时间,降低服务器的压力。

四. session

  1. session原理

    img

  2. session理解

    (1) Session是把数据保存到服务器端;

    (2) Session底层依然使用Cookie。

  3. 创建session

    HttpSession session = req.getSession();

    (1) 如果有session,那么直接拿到session;

    (2) 如果没有session,创建一个session,再拿到这个session;

  4. session的api

    • 设置值:session.setAttribute(String key, Object obj);
    • 获取指定的数据:req.getSession().getAttribute(String key);
    • 移除指定数据:根据一个key删除session中的一条记录,req.getSession().removeAttribute("name");
    • 销毁整个Session对象: req.getSession().invalidate();
  5. session的生命周期

    出生:创建Session对象;

    销毁:销毁session对象。

    ① 调用session对象的invalidate()方法:登出/注销

    ② 过期时间结束【从不操作开始算起】:最大非活动间隔

    (1) 代码方式:session.setMaxInactiveInterval(int s)

    (2) web.xml方式:,单位是分钟

    1
    2
    3
    4
     全局session时间 默认30分钟  
    <session-config>
    <session-timeout>30</session-timeout>
    </session-config>

    (3) 默认是30分钟,在Tomcat的web.xml查看

  6. session优缺点

    • 优点:
      • 由于session是将数据保存在服务器端,安全性高相对较高;
      • 大小相对于Cookie来说大得多;
      • 数据类型没有限制;
    • 缺点:
      • 数据量太大,会影响服务器的性能

五. 用户登录主要功能代码案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;

@Override
public AjaxResult getUser(User user, HttpSession session, Integer remember, HttpServletResponse resp) {
User u = userMapper.getUser(user);
if (u == null) {
return AjaxResult.error("登录失败:用户名或密码错误!");
// throw new RuntimeException("登录失败:用户名或密码错误!");
} else {
//存入session
session.setAttribute("USER_INFO", u);
if (remember != null) {
//响应cookie给浏览器
final Cookie c1 = new Cookie("username", u.getUsername());
final Cookie c2 = new Cookie("password", u.getPassword());
//设置有效期
c1.setMaxAge(60 * 60 * 24 * 7);
c2.setMaxAge(60 * 60 * 24 * 7);
//设置作用域
c1.setPath("/");
c2.setPath("/");
resp.addCookie(c1);
resp.addCookie(c2);
} else {//清空cookie
//响应cookie给浏览器
final Cookie c1 = new Cookie("username", u.getUsername());
final Cookie c2 = new Cookie("password", u.getPassword());
//设置有效期
c1.setMaxAge(0);
c2.setMaxAge(0);
//设置作用域
c1.setPath("/");
c2.setPath("/");
resp.addCookie(c1);
resp.addCookie(c2);
}
return AjaxResult.success();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
$(function () {//页面加载事件
//记住密码
remember();
$('#loginButton').click(function () {
login();
});
/**
*通过回车实现登录
* e表示事件源 keypress就是一个事件源 13表示键盘回车符代码
*/
$(document).on('keypress', function (e) {
if (e.keyCode == 13) {
login();
}
})

function login() {//登录函数
//通过表单发送Ajax请求
$('#loginForm').ajaxSubmit({
success: function (res) {
if (res.success) {
//登录成功
location.href = "/system/index";
} else {
alert(res.msg);
}
}
});
}

//记住密码
function remember() {
if (document.cookie.indexOf('username') != -1) {//存在cookie
//document.cookie='username=root; password=123'
var username = document.cookie.split(';')[0].split('=')[1];
var password = document.cookie.split(';')[1].split('=')[1];
//设置默认值
$('#username').val(username);
$('#password').val(password);
$('#remember').prop('checked', true);
}
}
})