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,如需转载请自行联系原作者

相关文章
|
2月前
|
人工智能 前端开发 Java
2025年WebStorm高效Java开发全指南:从配置到实战
WebStorm 2025不仅是一款强大的JavaScript IDE,也全面支持Java开发。本文详解其AI辅助编程、Java特性增强及性能优化,并提供环境配置、高效开发技巧与实战案例,助你打造流畅的全栈开发体验。
203 4
|
2月前
|
前端开发 JavaScript Java
Java 开发中 Swing 界面嵌入浏览器实现方法详解
摘要:Java中嵌入浏览器可通过多种技术实现:1) JCEF框架利用Chromium内核,适合复杂网页;2) JEditorPane组件支持简单HTML显示,但功能有限;3) DJNativeSwing-SWT可内嵌浏览器,需特定内核支持;4) JavaFX WebView结合Swing可完美支持现代网页技术。每种方案各有特点,开发者需根据项目需求选择合适方法,如JCEF适合高性能要求,JEditorPane适合简单展示。(149字)
213 1
|
2月前
|
安全 Java 领域建模
Java 17 探秘:不容错过的现代开发利器
Java 17 探秘:不容错过的现代开发利器
|
29天前
|
安全 Oracle Java
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
110 0
JAVA高级开发必备·卓伊凡详细JDK、JRE、JVM与Java生态深度解析-形象比喻系统理解-优雅草卓伊凡
|
2月前
|
并行计算 Java API
Java List 集合结合 Java 17 新特性与现代开发实践的深度解析及实战指南 Java List 集合
本文深入解析Java 17中List集合的现代用法,结合函数式编程、Stream API、密封类、模式匹配等新特性,通过实操案例讲解数据处理、并行计算、响应式编程等场景下的高级应用,帮助开发者提升集合操作效率与代码质量。
114 1
|
2月前
|
安全 Java API
Java 17 及以上版本核心特性在现代开发实践中的深度应用与高效实践方法 Java 开发实践
本项目以“学生成绩管理系统”为例,深入实践Java 17+核心特性与现代开发技术。采用Spring Boot 3.1、WebFlux、R2DBC等构建响应式应用,结合Record类、模式匹配、Stream优化等新特性提升代码质量。涵盖容器化部署(Docker)、自动化测试、性能优化及安全加固,全面展示Java最新技术在实际项目中的应用,助力开发者掌握现代化Java开发方法。
92 1
|
2月前
|
IDE Java API
Java 17 新特性与微服务开发的实操指南
本内容涵盖Java 11至Java 17最新特性实战,包括var关键字、字符串增强、模块化系统、Stream API、异步编程、密封类等,并提供图书管理系统实战项目,帮助开发者掌握现代Java开发技巧与工具。
121 1
|
2月前
|
安全 Java 测试技术
Java 大学期末实操项目在线图书管理系统开发实例及关键技术解析实操项目
本项目基于Spring Boot 3.0与Java 17,实现在线图书管理系统,涵盖CRUD操作、RESTful API、安全认证及单元测试,助力学生掌握现代Java开发核心技能。
91 0