Java EE WEB工程师培训-JDBC+Servlet+JSP整合开发之16.Cookie

简介:
–Cookie 简介 
–设置Cookie 
–创建Cookie 
–获得Cookie 
–Cookie应用实例 
• 使用cookie检测初访者 
• 自动登录
################Michael分割线######################
–Cookie 简介 
• Cookie 是保存在客户端的一个“键-值”对,用来标识用户的一些信息 
• Cookie的应用 
–在电子商务会话中标识用户 
–对站点进行定制 
–定向广告
• 创建Cookie 
–调用Cookie的构造函数,给出cookie的名称和cookie的值,二者都是字符串 
• Cookie c = new Cookie("userID", "a1234"); 
–设置最大时效 
• 如果要告诉浏览器将cookie存储到磁盘上,而非仅仅保存在内存中,使用setMaxAge (参数为秒数) 
• c.setMaxAge(60*60*24*7); // One week 
–将Cookie放入到HTTP响应 
• response.addCookie(c);
image
• 获得Cookie 
–调用request.getCookies 
•这会得到Cookie对象组成的数组 
• 在这个数组中循环,调用每个对象的getName,直到找到想要的cookie为止
image
TestCookiesServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

import javax.servlet.ServletException;    
import javax.servlet.http.Cookie;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

public  class TestCookiesServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public TestCookiesServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                 //Setting cookie    
                 //创建Cookie    
                Cookie c1 =  new Cookie( "c1", "cv1");    
                Cookie c2 =  new Cookie( "c2", "cv2");    
                 //设置Cookie时效    
                c1.setMaxAge(60*60*24);    
                c2.setMaxAge(60*60*24);    
                 //添加Cookie    
                response.addCookie(c1);    
                response.addCookie(c2);    
                 //getting cookie    
                Cookie[] cookies = request.getCookies();    
                String name = "";    
                String value = "";    
                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</TITLE></HEAD>");    
                out.println("    <BODY>");    
                if(cookies!=null&&cookies.length>0){    
                        for(int i=0;i<cookies.length;i++){    
                                name = cookies[i].getName();    
                                value = cookies[i].getValue();    
                                out.println(name+":"+value);    
                        }    
                }    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


image
web.xml
<? xml  version ="1.0"  encoding ="UTF-8" ?>    
< web-app  version ="2.4"    
         xmlns ="http://java.sun.com/xml/ns/j2ee"    
         xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"    
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >    
     < servlet >    
         < description >This is the description of my J2EE component </ description >    
         < display-name >This is the display name of my J2EE component </ display-name >    
         < servlet-name >TestCookiesServlet </ servlet-name >    
         < servlet-class >com.michael.servlet.TestCookiesServlet </ servlet-class >    
     </ servlet >    

     < servlet-mapping >    
         < servlet-name >TestCookiesServlet </ servlet-name >    
         < url-pattern >/servlet/TestCookiesServlet </ url-pattern >    
     </ servlet-mapping >    

</ web-app > 
image
测试一下
image
image
• Cookie应用实例 
–使用cookie检测初访者
image
TestCookiesServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

import javax.servlet.ServletException;    
import javax.servlet.http.Cookie;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

public  class TestCookiesServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public TestCookiesServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                 /**    
                //Setting cookie    
                //创建Cookie    
                Cookie c1 = new Cookie("c1","cv1");    
                Cookie c2 = new Cookie("c2","cv2");    
                //设置Cookie时效    
                c1.setMaxAge(60*60*24);    
                c2.setMaxAge(60*60*24);    
                //添加Cookie    
                response.addCookie(c1);    
                response.addCookie(c2);    
                //getting cookie    
                Cookie[] cookies = request.getCookies();    
                String name = "";    
                String value = "";    
                */
    
                 //使用cookie检测初访者    
                 boolean newbie =  true;    
                Cookie[] cookies = request.getCookies();    
                 if(cookies!= null){    
                         for( int i=0;i<cookies.length;i++){    
                                Cookie c = cookies[i];    
                                 if((c.getName().equals( "repeatVisitor"))&&(c.getValue().equals( "yes"))){    
                                        newbie =  false;    
                                         break;    
                                }    
                                String title;    
                                 if(newbie){    
                                        Cookie returnVisitorCookie =  new Cookie( "repeatVisitor", "yes");    
                                        returnVisitorCookie.setMaxAge(60*60*24*365);    
                                        response.addCookie(returnVisitorCookie);    
                                        title =  "Welcome Aboard";    
                                } else{    
                                        title =  "Welcome Back";    
                                }    
                                System.out.println(title);    
                        }    
                }    
                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</TITLE></HEAD>");    
                out.println("    <BODY>");    
                /*    
                if(cookies!=null&&cookies.length>0){    
                        for(int i=0;i<cookies.length;i++){    
                                name = cookies[i].getName();    
                                value = cookies[i].getValue();    
                                out.println(name+":"+value);    
                        }    
                }    
                */
    
                out.println("    </BODY>");    
                out.println("</HTML>");    
                out.flush();    
                out.close();    
        }    

        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    


image
image
–自动登录
image
image
  InitServlet.java
package com.michael.servlet;    
import java.io.IOException;    
import javax.servlet.ServletException;    
import javax.servlet.http.Cookie;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

public  class InitServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public InitServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request,response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                 //获取Cookie    
                Cookie[] cookies = request.getCookies();    
                 if(cookies!= null&&cookies.length>0){    
                         for( int i=0;i<cookies.length;i++){    
                                String name =cookies[i].getName();    
                                 if(name!= null&&name.equals( "username")){    
                                        String value = cookies[i].getValue();    
                                        request.setAttribute( "un",value);    
                                }    
                                 if(name!= null&&name.equals( "password")){    
                                        String value = cookies[i].getValue();    
                                        request.setAttribute( "pw",value);    
                                }    
                        }    
                }    

                request.getRequestDispatcher( "/login.jsp").forward(request, response);    
        }    

         /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
         public  void init()  throws ServletException {    
                 // Put your code here    
        }    


login.jsp 
<%@ page language= "java"  import= "java.util.*" pageEncoding= "gbk"%>    
<%    
String path = request.getContextPath();    
String basePath = request.getScheme()+ "://"+request.getServerName()+":"+request.getServerPort()+path+"/";    
%>    

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <base href="<%=basePath%>">    
        <title>My JSP 'login.jsp' starting page</title>    
        <meta http-equiv="pragma" content="no-cache">    
        <meta http-equiv="cache-control" content="no-cache">    
        <meta http-equiv="expires" content="0">         
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="This is my page">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    

    </head>    
    <body>    
        <form name="f1" id="f1" action="/Servlet_Cookies/servlet/LoginServlet" method="post">    
            <table border="0">    
                <tr>    
                    <td>用户名称:</td>    
                    <td><input type="text" name="username" value="${un}"></td>    
                </tr>    
                <tr>    
                    <td>用户密码:</td>    
                    <td><input type="password" name="password" value="${pw}"></td>    
                </tr>    
                <tr>    
                    <td>一周自动登录:</td>    
                    <td colspan="2"><input type="checkbox" name="isAuto" value="1"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="登录"></td>    
                </tr>    
            </table>    
        </form>    
    </body>    
</html> 
LoginServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    

import javax.servlet.ServletException;    
import javax.servlet.http.Cookie;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

public  class LoginServlet  extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public LoginServlet() {    
                 super();    
        }    

         /**    
         * Destruction of the servlet. <br>    
         */
    
         public  void destroy() {    
                 super.destroy();  // Just puts "destroy" string in log    
                 // Put your code here    
        }    

         /**    
         * The doGet method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to get.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doGet(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    

                doPost(request, response);    
        }    

         /**    
         * The doPost method of the servlet. <br>    
         *    
         * This method is called when a form has its tag value method equals to post.    
         *    
         * @param request the request send by the client to the server    
         * @param response the response send by the server to the client    
         * @throws ServletException if an error occurred    
         * @throws IOException if an error occurred    
         */
    
         public  void doPost(HttpServletRequest request, HttpServletResponse response)    
                         throws ServletException, IOException {    
                String username = request.getParameter( "username");    
                String password = request.getParameter( "password");    
                String isAuto = request.getParameter( "isAuto");    
                 if(isAuto!= null&&isAuto.equals( "1")){    
                        Cookie usernameCookie =  new Cookie( "username",username);    
                        Cookie passwordCookie =  new Cookie( "password",password);    
                        usernameCookie.setMaxAge(60*60*24*7);    
                        passwordCookie.setMaxAge(60*60*24*7);    
                        response.addCookie(usernameCookie);    
                        response.addCookie(passwordCookie);    
                }    
                 //页面跳转    
                request.getRequestDispatcher( "/welcome.html").forward(request, response);    
        }    

         /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occure    
         */
    
         public  void init()  throws ServletException {    
                 // Put your code here    
        }    


welcome.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >    
< html >    
     < head >    
         < title >MyHtml.html </title>    
         < meta  http-equiv ="keywords"  content ="keyword1,keyword2,keyword3" >    
         < meta  http-equiv ="description"  content ="this is my page" >    
         < meta  http-equiv ="content-type"  content ="text/html; charset=UTF-8" >    
         <! --<link rel="stylesheet" type="text/css" href="./styles.css">-->    

     </head>    
     < body >    
         < h1 >Welcome you! </h1>    
     </body>    
</html> 
image
################Michael分割线######################








本文转自redking51CTO博客,原文链接:http://blog.51cto.com/redking/174725,如需转载请自行联系原作者

相关文章
|
3天前
|
缓存 Java Spring
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
文章比较了在Servlet和Spring Boot中获取Cookie、Session和Header的方法,并提供了相应的代码实例,展示了两种方式在实际应用中的异同。
12 3
servlet和SpringBoot两种方式分别获取Cookie和Session方式比较(带源码) —— 图文并茂 两种方式获取Header
|
16天前
|
存储 搜索推荐 UED
探索研究Servlet Cookie 处理
【9月更文挑战第25天】
24 0
|
2月前
|
前端开发 安全 Java
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
19 0
|
4月前
|
前端开发 安全 Java
Java服务器端开发实战:利用Servlet和JSP构建动态网站
【6月更文挑战第23天】**Servlet和JSP在Java Web开发中扮演关键角色。Servlet处理业务逻辑,管理会话,JSP则结合HTML生成动态页面。两者协同工作,形成动态网站的核心。通过Servlet的doGet()方法响应请求,JSP利用嵌入式Java代码创建动态内容。实战中,Servlet处理数据后转发给JSP展示,共同构建高效、稳定的网站。虽然新技术涌现,Servlet与JSP仍为Java Web开发的基石,提供灵活且成熟的解决方案。**
66 8
|
4月前
|
搜索推荐 Java 数据库连接
探索Java Web开发:Servlet与JSP的协同工作原理
【6月更文挑战第23天】Java Web开发中,Servlet和JSP协同打造动态网站。Servlet是服务器端的Java程序,处理HTTP请求并执行复杂逻辑;JSP则结合HTML和Java,生成动态内容。Servlet通过`doGet()`等方法响应请求,JSP在首次请求时编译成Servlet。两者常搭配使用,Servlet处理业务,JSP专注展示,通过`RequestDispatcher`转发实现数据渲染。这种组合是Java Web应用的基础,即使新技术涌现,其价值仍然重要,为开发者提供了强大的工具集。
50 7
|
4月前
|
存储 设计模式 搜索推荐
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
27 1
|
4月前
|
API
获得servlet相关API,获得请求头和cookie-spring23
获得servlet相关API,获得请求头和cookie-spring23
|
4月前
|
XML 前端开发 Java
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(上)
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(上)
26 0
|
2月前
|
SQL Java 数据库
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上
该博客文章介绍了在JSP应用中使用Servlet查询SQL Server数据库的表信息,并通过JavaBean封装图书信息,将查询结果展示在Web页面上的方法。
jsp中使用Servlet查询SQLSERVER数据库中的表的信息,并且打印在屏幕上
|
2月前
|
供应链 前端开发 Java
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)
这篇文章通过一个服装库存管理系统的实例,展示了在Spring Boot项目中使用Ajax、JSON、layui、MVC架构和iframe等技术,涵盖了注册登录、权限管理、用户管理、库存管理等功能,并提供了系统运行环境和技术要求的详细说明。
JSP+servlet+mybatis+layui服装库存管理系统(大三上学期课程设计)