servlet-会话(cookie与session)

servlet会话技术

会话技术

两种会话:cookie,session

  • 会话:当用户打开浏览器的时候,访问不同的资源( url ),用户将浏览器关闭,可以认为这是一次会话.
  • 作用:http 协议是一个无状态的协议, http 记录不了上次访问平台时间等信息的;用户在访问过程中可能会产生一些数据,所以通过 cookie 会话将常用数据保存起来
    如:用户登录( session 用得最多,信息保存安全),访问记录( cookie 会话使用多,保存信息不关乎安全)
  • 分类:
    cookie:浏览器端会话技术[针对浏览器,安全系数低](记录常用信息,又不影响安全的信息)
    session:服务器端会话技术[针对服务器,安全性高](主要:用户登录)

cookie 是由服务器生成,通过 response 将 cookie 写回浏览器,保留在浏览器上,下一次访问,浏览器根据一定规则携带不同的 cookie (通过 request 的头 cookie ),服务器就可以接收到对应的cookie【如准考证号,唯一性】。

1).cookie 创建:

new Cookie(String key,String value)

2).写回至浏览器:

response.addCookie(Cookie c)

3).获取 cookie(数组):

Cookie[] request.getCookies()

4).cookie 常用方法:

getName():获取 cookie 的 key(名称)

getValue:获取 cookie 值

创建Cookie

index.jsp

xml 复制代码
    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>

CookieServlet

java 复制代码
@WebServlet(name = "creatCookie", value = "/creatCookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        //创建Cookie
        Cookie id = new Cookie("id", "1");
        Cookie shop = new Cookie("shop", "XIAOMI");
//      如果 cookie 需要写入中文,用 new Cookie("aNameKey", URLEncoder.encode("李","utf-8"));方式
//      如果取 cookie 中文值用 URLDecoder.decode(cookie.getValue(), "UTF-8");
        Cookie shopNmae = new Cookie("shopName", URLEncoder.encode("小米","utf-8"));

        //回显到浏览器
        response.addCookie(id);
        response.addCookie(shop);
        response.addCookie(shopNmae);

        response.getWriter().append("Cookie已创建");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

获取Cookie

index.jsp

html 复制代码
    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>
    <br>
    <a href="<%=request.getContextPath()%>/showCookie">获取cookie值</a>

showCookie

java 复制代码
@WebServlet(name = "showCookie", value = "/showCookie")
public class ShowCookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
//      如果 cookie 需要写入中文,用 new Cookie("aNameKey", URLEncoder.encode("李","utf-8"));方式
//      如果取 cookie 中文值用 URLDecoder.decode(cookie.getValue(), "UTF-8");
//回显到浏览器
            response.getWriter()
                    .append(cookie.getName() + "==" + URLDecoder.decode(cookie.getValue(),"utf-8"))
                    .append("<br>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

session

1).服务器( tomcat )端会话技术

2).获取一个session:

HttpSession request.getSession()

3).域对象:

xxxAttribute(setAttribute,getAttribute)

销毁:

a).服务器非正常关闭(突然宕机)

b).session 超时

默认时间超时:30分钟 tomcat 里的 web.xml 有配置

手动设置超时:setMaxInactiveInterval(秒)

c).手动编写清除 session 会话方法:

清除所有:session.invalidate();

清除单个:session.remove("username");(掌握)

创建session

index.jsp

html 复制代码
    <a href="<%=request.getContextPath()%>/creatCookie">创建Cookie</a>
    <br>
    <a href="<%=request.getContextPath()%>/showCookie">获取cookie值</a>
    <br>
    <a href="login.jsp">登录</a>

login.jsp

html 复制代码
  <form action="<%=request.getContextPath()%>/login" method="post">
    <label>用户名:</label><input type="text" name="username">
    <br>
    <label>密码:</label><input type="password" name="password">
    <br>
    <input type="submit" value="登录">
  </form>
  <br>
  <a href="/f_session/cleitme">清空itme会话</a>

LoginServlet

java 复制代码
@WebServlet(name = "login", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取login.jsp传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //假定数据库存有两个对象
        List<User> users = new ArrayList<>();
        users.add(new User("zhangsan", "123"));
        users.add(new User("lisi","1234"));

        if(users.size()>0){//判断数据库中是否有数据
            for (User user : users) {//遍历数据库
                if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                    //创建session
                    HttpSession session = request.getSession();
                    //设置域对象
                    session.setAttribute("usersession", user);
                    response.sendRedirect(request.getContextPath() + "/redu");

                }
            }
        }
    }
}

获取session

RedurectServket

javascript 复制代码
@WebServlet("/redu")
public class RedurectServket extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得session
        HttpSession session = request.getSession();
        //获得域对象数据
        User ussess = (User) session.getAttribute("usersession");
        response.getWriter().append(ussess.getUsername()+",===,"+ussess.getPassword());
        System.out.println("执行方法");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request,response);
    }
}


清除会话

login.jsp

html 复制代码
  <form action="<%=request.getContextPath()%>/login" method="post">
    <label>用户名:</label><input type="text" name="username">
    <br>
    <label>密码:</label><input type="password" name="password">
    <br>
    <input type="submit" value="登录">
  </form>
  <br>
  <a href="<%=request.getContextPath()%>/cleitme">清空itme会话</a>

ClearItmeServlet

java 复制代码
@WebServlet("/cleitme")
public class ClearItmeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        HttpSession session = request.getSession();

        //session.invalidate()//手动清空所有
        session.removeAttribute("usersession");//工作时使用这样指定方式移除以避免会话全部清空
        response.getWriter().print("usersession此会话已清除");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
相关推荐
全栈老实人_2 分钟前
考研互学互助系统|Java|SSM|VUE| 前后端分离
java·开发语言·tomcat·maven
天天进步20156 分钟前
Java全栈项目实战:校园报修服务系统
java·开发语言
Themberfue32 分钟前
Java 网络原理 ①-IO多路复用 || 自定义协议 || XML || JSON
xml·java·开发语言·网络·计算机网络·json
wm104337 分钟前
JavaEE 3大组件 Listener Servlet Filter
java·servlet·java-ee
疯一样的码农1 小时前
基于Spring Boot + Vue3实现的在线商品竞拍管理系统源码+文档
java·spring boot·后端
m0_748251352 小时前
【SpringBoot】日志文件
java·spring boot·spring
m0_748234712 小时前
Java-33 深入浅出 Spring - FactoryBean 和 BeanFactory BeanPostProcessor
java·开发语言·spring
知初~3 小时前
java相关学习文档或网站整理
java·开发语言·学习
码农小灰3 小时前
什么是缓存穿透、缓存击穿、缓存雪崩,在项目中是如何解决和预防?它们分别会带来什么危害?
java·缓存
a栋栋栋3 小时前
apifox
java·前端·javascript