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);
    }
}
相关推荐
魔道不误砍柴功1 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
NiNg_1_2341 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
闲晨1 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
测开小菜鸟2 小时前
使用python向钉钉群聊发送消息
java·python·钉钉
P.H. Infinity3 小时前
【RabbitMQ】04-发送者可靠性
java·rabbitmq·java-rabbitmq
生命几十年3万天3 小时前
java的threadlocal为何内存泄漏
java
caridle4 小时前
教程:使用 InterBase Express 访问数据库(五):TIBTransaction
java·数据库·express
^velpro^4 小时前
数据库连接池的创建
java·开发语言·数据库
苹果醋34 小时前
Java8->Java19的初步探索
java·运维·spring boot·mysql·nginx
秋の花4 小时前
【JAVA基础】Java集合基础
java·开发语言·windows