JAVA学习过程

cookie

2017-10-10  本文已影响0人  _String_

通过cookie类实例化cookie对象,使用response.addCokie()写入cookie写入cookie示例代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取用户输入表单
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String[] hobby = request.getParameterValues("ah");
        String gw = request.getParameter("zw");
        String memo = request.getParameter("bz");
        Cookie c =new Cookie("username", name);
        byte[] by = Base64.getEncoder().encode(password.getBytes());
        Cookie p = new Cookie("passwd",new String(by));
        p.setMaxAge(60*60);
        c.setMaxAge(60*60);
        response.addCookie(c);
        response.addCookie(p);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet Form</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.println(name);
        out.println(password);
        out.println(sex);
        for(String x:hobby){
            out.println(x);
        }
        out.println(gw);
        out.println(memo);
        
        out.println("set cookie");
        out.println("  </BODY>");
        out.println("</HTML>");
写入cookie

servlet读取cookie使用request.getCookies()读取cookie,该方法返回一些列表,需要使用循环遍历该对象。读取代码如下:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        javax.servlet.http.Cookie[] cs = request.getCookies();
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        if(cs != null &&cs.length>0){
            for(int i =0;i<cs.length;i++){
                javax.servlet.http.Cookie c = cs[i];
                out.println(c.getName()+":"+c.getValue());
            }
        }else{
            out.println("no cookie");
        }
        
        
    }
servlet读取cookie 读取cookie
上一篇下一篇

猜你喜欢

热点阅读