Java教程

JavaWeb中Cookie与Session的使用

本文主要是介绍JavaWeb中Cookie与Session的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Cookie的存值、取值与注销

public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符集,防止乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        // 服务器从客户端获取Cookie
        Cookie[] cookies = req.getCookies();

        if(cookies!=null){
            out.write("您上次的访问时间是:");
            for (Cookie cookie : cookies) {
                Cookie co = cookie;
                if(co.getName().equals("lastTime")){
                    long l = Long.parseLong(co.getValue());
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        }else{
            out.write("这是你第一次访问本站");
        }

        Cookie cookie = new Cookie("lastTime",String.valueOf(System.currentTimeMillis()));
        // 设置cookie有效期为一天,设置有效期为0,可以手动删除cookie,即注销cookie
        cookie.setMaxAge(24*60*60);

        // 服务器为客户端设置Cookie
        resp.addCookie(cookie);
    }

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

Session的存值、取值与注销

public class SessionDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置字符集,防止乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        // 浏览器从服务器得到session
        HttpSession session = req.getSession();
        // 给session中存东西
        session.setAttribute("name","lyon");
        // 获取session的ID
        String sessionId = session.getId();
        // 判断session是不是空的
        if(session.isNew()){
            resp.getWriter().write("session创建成功,ID:"+sessionId);
        }else{
            resp.getWriter().write("session已经在服务器中存在,ID:"+sessionId);
        }


        /** session创建的时候做了什么?
         *  1. Cookie cookie = new Cookie("name", "lyon");
         *  2. resp.addCookie(cookie);
         */


        // 取session的值
        Object name = session.getAttribute("name");
        resp.getWriter().write("<br />"+"本次取得的session值为:"+name.toString());
        System.out.println(name.toString());

        // 设置session的值为对象类型,并取值
        session.setAttribute("person",new Person("lyon",18));
        Person person = (Person) session.getAttribute("person");
        resp.getWriter().write("<br />"+"本次从session中取到Person对象的值为:"+person.toString());

        // 手动注销session
        session.invalidate();
        /** web.xml中注销通过设置有效时间
         *
         *   <session-config>
         *   <!--  15分钟后session自动失效  -->
         *     <session-timeout>15</session-timeout>
         *   </session-config>
         */

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
这篇关于JavaWeb中Cookie与Session的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!