JavaWeb16.4【Cookie&Session:JSP入门】

 

 

 

 index.jsp

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: yubaby
 4   Date: 2021/7/2
 5   Time: 14:35
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10   <head>
11     <title>$Title$</title>
12   </head>
13   <body>
14 
15     <%
16       System.out.println("hello jsp, i'm back");  //输出到IDEA控制台
17     %>
18     <h1>hi,jsp</h1> <%--输出到浏览器页面--%>
19 
20 
21     <% response.getWriter().write("response....."); %>
22 
23     <% //在Servlet的service方法中
24       System.out.println("hello jsp, i'm back");
25       int i = 5;
26 
27       String contextPath = request.getContextPath();    //request、response、out为内置对象,不用声明,可以直接用,因为servlet类中定义了
28       out.print(contextPath); // /day16
29     %>
30     <%! //在Servlet类的成员位置
31       int i = 3;
32     %>
33     <%= //输出到页面上
34             i //5,因为就近原则,service方法中定义的局部变量i的作用域较小
35     %>
36     <%= "hello" %>
37 
38     <% response.getWriter().write("response*****"); %>
39   </body>
40 </html>

 

 

 

 

 

 index_jsp.java

  1 /*
  2  * Generated by the Jasper component of Apache Tomcat
  3  * Version: Apache Tomcat/8.5.31
  4  * Generated at: 2021-07-02 12:33:12 UTC
  5  * Note: The last modified time of this file was set to
  6  *       the last modified time of the source file after
  7  *       generation to assist with modification tracking.
  8  */
  9 package org.apache.jsp;
 10 
 11 import javax.servlet.*;
 12 import javax.servlet.http.*;
 13 import javax.servlet.jsp.*;
 14 
 15 public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
 16     implements org.apache.jasper.runtime.JspSourceDependent,
 17                  org.apache.jasper.runtime.JspSourceImports {
 18 
 19  //在Servlet类的成员位置
 20       int i = 3;
 21     
 22   private static final javax.servlet.jsp.JspFactory _jspxFactory =
 23           javax.servlet.jsp.JspFactory.getDefaultFactory();
 24 
 25   private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
 26 
 27   private static final java.util.Set<java.lang.String> _jspx_imports_packages;
 28 
 29   private static final java.util.Set<java.lang.String> _jspx_imports_classes;
 30 
 31   static {
 32     _jspx_imports_packages = new java.util.HashSet<>();
 33     _jspx_imports_packages.add("javax.servlet");
 34     _jspx_imports_packages.add("javax.servlet.http");
 35     _jspx_imports_packages.add("javax.servlet.jsp");
 36     _jspx_imports_classes = null;
 37   }
 38 
 39   private volatile javax.el.ExpressionFactory _el_expressionfactory;
 40   private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
 41 
 42   public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
 43     return _jspx_dependants;
 44   }
 45 
 46   public java.util.Set<java.lang.String> getPackageImports() {
 47     return _jspx_imports_packages;
 48   }
 49 
 50   public java.util.Set<java.lang.String> getClassImports() {
 51     return _jspx_imports_classes;
 52   }
 53 
 54   public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
 55     if (_el_expressionfactory == null) {
 56       synchronized (this) {
 57         if (_el_expressionfactory == null) {
 58           _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
 59         }
 60       }
 61     }
 62     return _el_expressionfactory;
 63   }
 64 
 65   public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
 66     if (_jsp_instancemanager == null) {
 67       synchronized (this) {
 68         if (_jsp_instancemanager == null) {
 69           _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
 70         }
 71       }
 72     }
 73     return _jsp_instancemanager;
 74   }
 75 
 76   public void _jspInit() {
 77   }
 78 
 79   public void _jspDestroy() {
 80   }
 81 
 82   public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
 83       throws java.io.IOException, javax.servlet.ServletException {
 84 
 85     final java.lang.String _jspx_method = request.getMethod();
 86     if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
 87       response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
 88       return;
 89     }
 90 
 91     final javax.servlet.jsp.PageContext pageContext;
 92     javax.servlet.http.HttpSession session = null;
 93     final javax.servlet.ServletContext application;
 94     final javax.servlet.ServletConfig config;
 95     javax.servlet.jsp.JspWriter out = null;
 96     final java.lang.Object page = this;
 97     javax.servlet.jsp.JspWriter _jspx_out = null;
 98     javax.servlet.jsp.PageContext _jspx_page_context = null;
 99 
100 
101     try {
102       response.setContentType("text/html;charset=UTF-8");
103       pageContext = _jspxFactory.getPageContext(this, request, response,
104                   null, true, 8192, true);
105       _jspx_page_context = pageContext;
106       application = pageContext.getServletContext();
107       config = pageContext.getServletConfig();
108       session = pageContext.getSession();
109       out = pageContext.getOut();
110       _jspx_out = out;
111 
112       out.write("\n");
113       out.write("\n");
114       out.write("<html>\n");
115       out.write("  <head>\n");
116       out.write("    <title>$Title$</title>\n");
117       out.write("  </head>\n");
118       out.write("  <body>\n");
119       out.write("\n");
120       out.write("    ");
121 
122       System.out.println("hello jsp, i'm back");  //输出到IDEA控制台
123     
124       out.write("\n");
125       out.write("    <h1>hi,jsp</h1> ");
126       out.write("\n");
127       out.write("\n");
128       out.write("\n");
129       out.write("    ");
130  response.getWriter().write("response....."); 
131       out.write("\n");
132       out.write("\n");
133       out.write("    ");
134  //在Servlet的service方法中
135       System.out.println("hello jsp, i'm back");
136       int i = 5;
137 
138       String contextPath = request.getContextPath();    //request、response、out为内置对象,不用声明,可以直接用,因为servlet类中定义了
139       out.print(contextPath); // /day16
140     
141       out.write("\n");
142       out.write("    ");
143       out.write("\n");
144       out.write("    ");
145       out.print( //输出到页面上
146             i //5,因为就近原则,service方法中定义的局部变量i的作用域较小
147     );
148       out.write("\n");
149       out.write("    ");
150       out.print( "hello" );
151       out.write("\n");
152       out.write("\n");
153       out.write("    ");
154  response.getWriter().write("response*****"); 
155       out.write("\n");
156       out.write("  </body>\n");
157       out.write("</html>\n");
158     } catch (java.lang.Throwable t) {
159       if (!(t instanceof javax.servlet.jsp.SkipPageException)){
160         out = _jspx_out;
161         if (out != null && out.getBufferSize() != 0)
162           try {
163             if (response.isCommitted()) {
164               out.flush();
165             } else {
166               out.clearBuffer();
167             }
168           } catch (java.io.IOException e) {}
169         if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
170         else throw new ServletException(t);
171       }
172     } finally {
173       _jspxFactory.releasePageContext(_jspx_page_context);
174     }
175   }
176 }

apache-tomcat-8.5.31-src     tomcat部分源码

 

 HttpJspBase.java

 1 /*
 2  * Licensed to the Apache Software Foundation (ASF) under one or more
 3  * contributor license agreements.  See the NOTICE file distributed with
 4  * this work for additional information regarding copyright ownership.
 5  * The ASF licenses this file to You under the Apache License, Version 2.0
 6  * (the "License"); you may not use this file except in compliance with
 7  * the License.  You may obtain a copy of the License at
 8  *
 9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 package org.apache.jasper.runtime;
19 
20 import java.io.IOException;
21 
22 import javax.servlet.ServletConfig;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27 import javax.servlet.jsp.HttpJspPage;
28 
29 import org.apache.jasper.compiler.Localizer;
30 
31 /**
32  * This is the super class of all JSP-generated servlets.
33  *
34  * @author Anil K. Vijendran
35  */
36 public abstract class HttpJspBase extends HttpServlet implements HttpJspPage {
37 
38     private static final long serialVersionUID = 1L;
39 
40     protected HttpJspBase() {
41     }
42 
43     @Override
44     public final void init(ServletConfig config)
45         throws ServletException
46     {
47         super.init(config);
48         jspInit();
49         _jspInit();
50     }
51 
52     @Override
53     public String getServletInfo() {
54         return Localizer.getMessage("jsp.engine.info");
55     }
56 
57     @Override
58     public final void destroy() {
59         jspDestroy();
60         _jspDestroy();
61     }
62 
63     /**
64      * Entry point into service.
65      */
66     @Override
67     public final void service(HttpServletRequest request, HttpServletResponse response)
68         throws ServletException, IOException
69     {
70         _jspService(request, response);
71     }
72 
73     @Override
74     public void jspInit() {
75     }
76 
77     public void _jspInit() {
78     }
79 
80     @Override
81     public void jspDestroy() {
82     }
83 
84     protected void _jspDestroy() {
85     }
86 
87     @Override
88     public abstract void _jspService(HttpServletRequest request,
89                                      HttpServletResponse response)
90         throws ServletException, IOException;
91 }

 

 1 <%@ page import="java.net.URLDecoder" %>
 2 <%@ page import="java.util.Date" %>
 3 <%@ page import="java.text.SimpleDateFormat" %>
 4 <%@ page import="java.net.URLEncoder" %><%--
 5   Created by IntelliJ IDEA.
 6   User: yubaby
 7   Date: 2021/7/2
 8   Time: 20:49
 9   To change this template use File | Settings | File Templates.
10 --%>
11 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
12 <html>
13 <head>
14     <title>Title</title>
15 </head>
16 <body>
17 
18     <%
19         //设置响应的消息体的数据格式以及编码,防止中文乱码
20 //        response.setContentType("text/html;charset=utf-8");
21 
22         //1 获取所有cookie
23         Cookie[] cookies = request.getCookies();
24         boolean flag = false; //false表示没有名为lastTime的cookie
25 
26         //2 遍历cookie数组
27         if (cookies!=null && cookies.length>0){
28             for (Cookie cookie : cookies) {
29                 //3 获取cookie的名称
30                 String name = cookie.getName();
31                 //4 判断cookie名称是否为"lastTime"
32                 if ("lastTime".equals(name)){
33                     //有该cookie,说明不是第一次访问
34                     flag = true;
35 
36                     //(1) 响应数据
37                     String value = cookie.getValue();
38                     //-----------------------------------------
39                     //URL解码
40                     System.out.println("解码前:" + value);
41                     value = URLDecoder.decode(value, "utf-8");
42                     System.out.println("解码后:" + value);
43                     //-----------------------------------------
44 //                    response.getWriter().write("<h1>欢迎回来,您上次访问时间为:" + value + "</h1>");
45 //                    out.write("<h1>欢迎回来,您上次访问时间为:" + value + "</h1>"); //采用out输出不会影响页面布局
46     %> <%--jsp代码可以截断--%>
47 
48                         <h1>欢迎回来,您上次访问时间为:<%=value%></h1>
49 
50     <%
51                     //(2) 写回Cookie
52                     Date date = new Date();
53                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
54                     String str_date = sdf.format(date);
55                     //-----------------------------------------
56                     //URL编码(在tomcat8之后,cookie支持中文数据,但如空格等特殊字符还是不支持)
57                     System.out.println("编码前:" + str_date);
58                     str_date = URLEncoder.encode(str_date, "utf-8");
59                     System.out.println("编码后:" + str_date);
60                     //-----------------------------------------
61                     cookie.setValue(str_date);
62                     cookie.setMaxAge(60 * 60 * 24 * 30); //设置缓存一个月
63                     response.addCookie(cookie);
64 
65                     break;
66                 }
67             }
68         }
69 
70         if (cookies==null || cookies.length==0 || flag==false){
71             //无该cookie,说明是第一次访问
72             flag = true;
73 
74             //(1) 响应数据
75 //            response.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
76 //            out.write("<h1>您好,欢迎您首次访问</h1>");
77     %>
78 
79             <h1>您好,欢迎您首次访问</h1>
80 
81     <%
82             //(2) 写回Cookie
83             Date date = new Date();
84             SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
85             String str_date = sdf.format(date);
86             //-----------------------------------------
87             //URL编码
88             System.out.println("编码前:" + str_date);
89             str_date = URLEncoder.encode(str_date, "utf-8");
90             System.out.println("编码后:" + str_date);
91             //-----------------------------------------
92             Cookie c = new Cookie("lastTime", str_date);
93             c.setMaxAge(60 * 60 * 24 * 30); //设置缓存一个月
94             response.addCookie(c);
95         }
96     %>
97 
98 </body>
99 </html>

 

posted @ 2021-07-02 20:44  yub4by  阅读(36)  评论(0编辑  收藏  举报