├── .classpath
├── .gitignore
├── .project
├── .settings
├── .jsdtscope
├── org.eclipse.core.resources.prefs
├── org.eclipse.jdt.core.prefs
├── org.eclipse.wst.common.component
├── org.eclipse.wst.common.project.facet.core.xml
├── org.eclipse.wst.jsdt.ui.superType.container
└── org.eclipse.wst.jsdt.ui.superType.name
├── LICENSE
├── README.md
├── WebContent
├── META-INF
│ └── MANIFEST.MF
├── async
│ └── asyncThread.jsp
├── component
│ └── uploadfile
│ │ └── upload.jsp
├── counter.jsp
└── jspC.jsp
└── src
└── org
├── component
└── uploadfile
│ └── UploadServlet.java
├── jsp
└── Counter.java
├── servlet
├── HttpServletService.java
├── async
│ ├── AsyncServlet.java
│ └── AsyncThread.java
├── reqAndresp
│ ├── HelloWorldServletT.java
│ ├── LifeCircleServletT.java
│ └── SuperServiceServletT.java
└── sessionMngmt
│ ├── HttpSessionByCookieServletT.java
│ ├── HttpSessionMethodsServletT.java
│ └── HttpSessionServletT.java
└── tomcat
└── jsp
└── jasper
└── JspCompilerT.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.class
2 |
3 | # Mobile Tools for Java (J2ME)
4 | .mtj.tmp/
5 |
6 | # Package Files #
7 | *.jar
8 | *.war
9 | *.ear
10 |
11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12 | hs_err_pid*
13 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | servlet-core-learning
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.wst.jsdt.core.javascriptValidator
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 | org.eclipse.wst.common.project.facet.core.builder
20 |
21 |
22 |
23 |
24 | org.eclipse.wst.validation.validationbuilder
25 |
26 |
27 |
28 |
29 |
30 | org.eclipse.jem.workbench.JavaEMFNature
31 | org.eclipse.wst.common.modulecore.ModuleCoreNature
32 | org.eclipse.wst.common.project.facet.core.nature
33 | org.eclipse.jdt.core.javanature
34 | org.eclipse.wst.jsdt.core.jsNature
35 |
36 |
37 |
--------------------------------------------------------------------------------
/.settings/.jsdtscope:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//WebContent/jspC.jsp=UTF-8
3 | encoding/=UTF-8
4 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
4 | org.eclipse.jdt.core.compiler.compliance=1.7
5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
7 | org.eclipse.jdt.core.compiler.source=1.7
8 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.wst.common.component:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.wst.common.project.facet.core.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.wst.jsdt.ui.superType.container:
--------------------------------------------------------------------------------
1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary
--------------------------------------------------------------------------------
/.settings/org.eclipse.wst.jsdt.ui.superType.name:
--------------------------------------------------------------------------------
1 | Window
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # servlet-core-learning
2 | Servlet/JSP学习积累的例子,是Java EE初学者及Servlet/JSP核心技术巩固的最佳实践。
3 | 补充:还有Tomcat容器相关
4 |
5 | ## 作者与学习乐园
6 | 源码地址:我的[GitHub地址](https://github.com/JeffLi1993 "GitHub")
7 | 作者: [李强强](http://www.bysocket.com/ "李强强")
8 | QQ群:编程之美 365234583 [立即加入](http://jq.qq.com/?_wv=1027&k=Sx4s4U "编程之美")
9 |
10 | ## 项目结构
11 | - src 目录
12 | Servlet/JSP核心技术学习代码兼测试案例
13 | - test目录(测试包名与src目录保持一致)
14 | 对应学习代码包的详细测试案例
15 |
16 | 包目录:
17 |
18 | ├── 插件
19 | ├── org.component // 插件相关
20 | ├── Servlet JSP
21 | ├── org.jsp // jsp相关
22 | ├── org.servlet // Servlet相关
23 | ├── org.servlet.async // 异步调用
24 | ├── org.servlet.reqAndresp // 请求与响应
25 | ├── org.servlet.sessionMngmt // 会话管理
26 | ├── Tomcat
27 | ├── org.tomcat // tomcat相关
28 | │
29 | 拼命更新!顶!d=====( ̄▽ ̄*)b
30 |
31 | 插件相关详细目录:
32 |
33 | ├── README.md // 项目唯一详细文档
34 | ├── org.component // 插件相关
35 | ├── org.component.uploadfile // 插件-文件上传下载
36 | ├── UploadServlet.java // 文件上传类
37 | 拼命更新!顶!d=====( ̄▽ ̄*)b
38 |
39 | Servlet/Jsp相关详细目录:
40 |
41 | ├── README.md // 项目唯一详细文档
42 | ├── org.jsp // jsp相关
43 | ├── Counter.java // page指令之计数器累加器
44 | ├── org.servlet // Servlet相关
45 | ├── HttpServletService.java // HttpServlet的service方法实现
46 | ├── org.servlet.async // 异步调用
47 | ├── AsyncServlet.java // Servlet3.0提供的异步处理案例
48 | ├── AsyncThread.java // Servlet3.0提供的异步处理案例
49 | ├── org.servlet.reqAndresp // 请求与响应
50 | ├── HelloWorldServletT.java // HelloWrold案例
51 | ├── LifeCircleServletT.java // Servlet生命周期演示案例
52 | ├── SuperServiceServletT.java // super.service测试案例
53 | ├── org.servlet.sessionMngmt // 会话管理
54 | ├── HttpSessionByCookieServletT.java // HttpSession的默认Cookie实现案例
55 | ├── HttpSessionMethodsServletT.java // HttpSession的详细案例
56 | ├── HttpSessionServletT.java // HttpSession简单案例
57 | 拼命更新!顶!d=====( ̄▽ ̄*)b
58 |
59 | Tomcat相关详细目录:
60 |
61 | ├── README.md // 项目唯一详细文档
62 | ├── org.tomcat.jsp.jasper // Japser引擎
63 | ├── JspCompilerT.java // Jasper引擎编译JSP
64 | 拼命更新!顶!d=====( ̄▽ ̄*)b
65 |
66 | WebContent相关详细目录:
67 |
68 | ├── README.md // 项目唯一详细文档
69 | ├── /component // 插件相关
70 | ├── /component/uploadfile // 文件上传下载
71 | ├── upload.jsp // 文件上传JSP
72 | ├── /async // 异步调用
73 | ├── asyncThread.jsp // 异步调用JSP
74 | ├── counter.jsp // page指令之计数器累加器显示JSP
75 | ├── jspC.jsp // Jasper引擎编译JSP所需的JSP
76 | 拼命更新!顶!d=====( ̄▽ ̄*)b
77 |
78 |
--------------------------------------------------------------------------------
/WebContent/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Class-Path:
3 |
4 |
--------------------------------------------------------------------------------
/WebContent/async/asyncThread.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=UTF-8"
2 | pageEncoding="UTF-8"%>
3 |
4 | <%@ page import="java.util.Date" %>
5 |
6 |
7 |
8 | 异步调用界面
9 |
10 |
11 |
12 | Hello,${name}
13 |
14 | 异步业务开始时间 --- ${startDate}
15 | 异步业务结束时间 --- ${endDate}
16 |
17 |
--------------------------------------------------------------------------------
/WebContent/component/uploadfile/upload.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=UTF-8"
2 | pageEncoding="UTF-8"%>
3 |
5 |
6 |
7 |
8 | 上传文件
9 |
10 |
11 | 文件上传
12 |
13 |
19 |
20 |
--------------------------------------------------------------------------------
/WebContent/counter.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=UTF-8"
2 | pageEncoding="UTF-8"%>
3 | <%@page import="org.jsp.Counter" %>
4 |
5 |
6 |
7 |
8 | Insert title here
9 |
10 |
11 |
12 | 计数点 ->
13 | <%= Counter.getCount() %>
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/WebContent/jspC.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" contentType="text/html; charset=UTF-8"
2 | pageEncoding="ISO-8859-1"%>
3 |
4 |
5 |
6 |
7 | 当前日期
8 |
9 |
10 | 当前的日期是:<%=new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date())%>
11 |
12 |
--------------------------------------------------------------------------------
/src/org/component/uploadfile/UploadServlet.java:
--------------------------------------------------------------------------------
1 | package org.component.uploadfile;
2 |
3 | import java.io.File;
4 | import java.io.FileOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.PrintWriter;
8 | import java.io.RandomAccessFile;
9 |
10 | import javax.servlet.ServletException;
11 | import javax.servlet.annotation.WebServlet;
12 | import javax.servlet.http.HttpServlet;
13 | import javax.servlet.http.HttpServletRequest;
14 | import javax.servlet.http.HttpServletResponse;
15 | /*
16 | * Copyright [2015] [Jeff Lee]
17 | *
18 | * Licensed under the Apache License, Version 2.0 (the "License");
19 | * you may not use this file except in compliance with the License.
20 | * You may obtain a copy of the License at
21 | *
22 | * http://www.apache.org/licenses/LICENSE-2.0
23 | *
24 | * Unless required by applicable law or agreed to in writing, software
25 | * distributed under the License is distributed on an "AS IS" BASIS,
26 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27 | * See the License for the specific language governing permissions and
28 | * limitations under the License.
29 | */
30 |
31 | /**
32 | * @author Jeff Lee
33 | * @since 2015-7-20 21:45:25
34 | * 文件上传类
35 | * 访问目标:/WebContent/component/uploadfile/upload.jsp
36 | */
37 | @WebServlet( urlPatterns = "/upload.html" )
38 | public class UploadServlet extends HttpServlet {
39 |
40 | private static final long serialVersionUID = 1L;
41 |
42 | @Override
43 | protected void doPost(HttpServletRequest req, HttpServletResponse resp)
44 | throws ServletException, IOException {
45 | //////
46 | // 首先请求中的输入流,通过输出流输出到临时文件tempFileName
47 | //////
48 | // 从request中获取流信息
49 | InputStream fileStream = req.getInputStream();
50 | String tempFileName = "D:/tempFileName";
51 | File tempFile = new File(tempFileName);
52 |
53 | // 文件输出流指向这个临时文件
54 | FileOutputStream outputStream = new FileOutputStream(tempFile);
55 | byte[] buff = new byte[1024];// 分配1024个字节大小的内存给buff byte数组
56 | int n;
57 | while((n = fileStream.read(buff)) != -1) {
58 | outputStream.write(buff,0, n); // 读取1024个字节放到buff byte数组中
59 | }
60 |
61 | // 关闭输出流、输入流
62 | outputStream.close();
63 | fileStream.close();
64 |
65 | //////
66 | // RandomAccessFile 进行操作临时文件tempFileName
67 | // RandomAccessFile的使用在开源项目java-core-learning中有介绍使用
68 | //////
69 | // 读取临时文件
70 | RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "r");
71 | // 读取文件第二行,为了读取文件名
72 | int second = 1;
73 | String secondLine = null;
74 | while(second <= 2) {
75 | secondLine = randomAccessFile.readLine();
76 | second++;
77 | }
78 | // 获取文件名的位置
79 | int fileNamePosition = secondLine.lastIndexOf("filename");
80 | // 获取文件名称
81 | String fileName = secondLine.substring(fileNamePosition + 10,// "filename='" 十个字符
82 | secondLine.length() - 1);
83 |
84 | // 重定向文件指针到文件头
85 | randomAccessFile.seek(0);
86 | long startPosition = 0;
87 | int i = 1;
88 | // 获取文件内容起始位置
89 | while ((n = randomAccessFile.readByte()) != -1
90 | && i <= 4) { // 临时文件前面4行为表单属性
91 | if (n == '\n') {
92 | startPosition = randomAccessFile.getFilePointer();
93 | i++;
94 | }
95 | }
96 |
97 | // 重定向到临时文件末尾
98 | randomAccessFile.seek(randomAccessFile.length());
99 | long endPosition = randomAccessFile.getFilePointer();
100 | int j = 1;
101 | while ( endPosition > 0
102 | && j <= 2 ) { // 临时文件后面2行为表单属性
103 | endPosition--;
104 | randomAccessFile.seek(endPosition);
105 | if (randomAccessFile.readByte() == '\n') {
106 | j++;
107 | }
108 | }
109 |
110 | //////
111 | // 保存文件到上传文件路径
112 | //////
113 | // 设置保存上传文件路径目录
114 | String realPath = getServletContext().getRealPath("/") + "upload";
115 | File uploadDir = new File(realPath);
116 | // 如果路径不存在,创建路径
117 | if (!uploadDir.exists()) {
118 | uploadDir.mkdirs();
119 | }
120 | File uploadFile = new File(uploadDir,fileName);
121 | RandomAccessFile randomAccessFile2 = new RandomAccessFile(uploadFile, "rw");
122 |
123 | // 从临时文件中读取文件内容(从起始位置开始获取)
124 | randomAccessFile.seek(startPosition);
125 | while (startPosition < endPosition -1) {
126 | randomAccessFile2.write(randomAccessFile.readByte());
127 | startPosition = randomAccessFile.getFilePointer();
128 | }
129 |
130 | // 关输出输入流,删除临时文件
131 | randomAccessFile.close();
132 | randomAccessFile2.close();
133 | tempFile.delete();
134 |
135 | //////
136 | // 输出信息
137 | //////
138 | resp.setContentType("text/html;");
139 | resp.setCharacterEncoding("UTF-8");
140 | resp.setHeader("content-type","text/html;charset=UTF-8");
141 | PrintWriter out = resp.getWriter();
142 | out.println(" 绝对路径:" + uploadFile.getAbsolutePath());
143 | out.println("
可读:" + uploadFile.canRead());
144 | out.println("
可写:" + uploadFile.canWrite());
145 | out.println("
文件名:" + uploadFile.getName());
146 | out.println("
上级目录:" + uploadFile.getParent());
147 | out.println("
相对地址:" + uploadFile.getPath());
148 | out.println("
长度:" + uploadFile.length());
149 | out.println("
最近修改时间:" + uploadFile.lastModified());
150 | }
151 |
152 |
153 | }
154 |
--------------------------------------------------------------------------------
/src/org/jsp/Counter.java:
--------------------------------------------------------------------------------
1 | package org.jsp;
2 | /*
3 | * Copyright [2015] [Jeff Lee]
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * 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 | /**
19 | * @author Jeff Lee
20 | * @since 2015-7-20 21:45:25
21 | * page指令之计数器累加器
22 | * 文件目标:WebContent/counter.jsp
23 | */
24 | public class Counter {
25 | private static int count;
26 |
27 | public static synchronized int getCount() {
28 | count++;
29 | return count;
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/org/servlet/HttpServletService.java:
--------------------------------------------------------------------------------
1 | package org.servlet;
2 |
3 | import java.io.IOException;
4 | import java.text.MessageFormat;
5 | import java.util.ResourceBundle;
6 |
7 | import javax.servlet.ServletException;
8 | import javax.servlet.http.HttpServlet;
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | /*
12 | * Copyright [2015] [Jeff Lee]
13 | *
14 | * Licensed under the Apache License, Version 2.0 (the "License");
15 | * you may not use this file except in compliance with the License.
16 | * You may obtain a copy of the License at
17 | *
18 | * http://www.apache.org/licenses/LICENSE-2.0
19 | *
20 | * Unless required by applicable law or agreed to in writing, software
21 | * distributed under the License is distributed on an "AS IS" BASIS,
22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 | * See the License for the specific language governing permissions and
24 | * limitations under the License.
25 | */
26 |
27 | /**
28 | * @author Jeff Lee
29 | * @since 2015-9-3 19:30:56
30 | * HttpServlet的service方法实现
31 | */
32 | public class HttpServletService extends HttpServlet{
33 | private static final long serialVersionUID = -5630942344912714108L;
34 |
35 | private static final String METHOD_DELETE = "DELETE";
36 | private static final String METHOD_HEAD = "HEAD";
37 | private static final String METHOD_GET = "GET";
38 | private static final String METHOD_OPTIONS = "OPTIONS";
39 | private static final String METHOD_POST = "POST";
40 | private static final String METHOD_PUT = "PUT";
41 | private static final String METHOD_TRACE = "TRACE";
42 |
43 | private static final String HEADER_IFMODSINCE = "If-Modified-Since";
44 |
45 | private static final String LSTRING_FILE =
46 | "javax.servlet.http.LocalStrings";
47 | private static ResourceBundle lStrings =
48 | ResourceBundle.getBundle(LSTRING_FILE);
49 | /**
50 | * HTTP状态码304
51 | */
52 | public static final int SC_NOT_MODIFIED = 304;
53 |
54 | /**
55 | * 接收来自 public service方法的标准HTTP请求,
56 | * 并将它们分发给此类中定义的doXXX方法。
57 | */
58 | @SuppressWarnings("unused")
59 | protected void service(HttpServletRequest req, HttpServletResponse resp)
60 | throws ServletException, IOException {
61 | // 获取请求方法名
62 | String method = req.getMethod();
63 | // 如果是GET请求
64 | if (method.equals(METHOD_GET)) {
65 | // 上一次修改HttpServletRequest对象的时间
66 | long lastModified = getLastModified(req);
67 | // 没有改变
68 | if (lastModified == -1) {
69 | doGet(req, resp);
70 | } else {
71 | long ifModifiedSince;
72 | try {
73 | // 获取请求头中服务器修改时间
74 | ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
75 | } catch (IllegalArgumentException iae) {
76 | // 获取无效
77 | ifModifiedSince = -1;
78 | }
79 | // 如果请求头服务器修改时间迟
80 | if (ifModifiedSince < (lastModified / 1000 * 1000)) {
81 | // 设置修改HttpServletResponse对象的时间,重新设置浏览器的参数
82 | //maybeSetLastModified(resp, lastModified);
83 | // 调用doGet方法
84 | doGet(req, resp);
85 | } else {
86 | // 304 HTTP状态码
87 | resp.setStatus(SC_NOT_MODIFIED);
88 | }
89 | }
90 | } else if (method.equals(METHOD_HEAD)) {
91 | long lastModified = getLastModified(req);
92 | //maybeSetLastModified(resp, lastModified);
93 | doHead(req, resp);
94 | } else if (method.equals(METHOD_POST)) {
95 | doPost(req, resp);
96 | } else if (method.equals(METHOD_PUT)) {
97 | doPut(req, resp);
98 | } else if (method.equals(METHOD_DELETE)) {
99 | doDelete(req, resp);
100 | } else if (method.equals(METHOD_OPTIONS)) {
101 | doOptions(req,resp);
102 | } else if (method.equals(METHOD_TRACE)) {
103 | doTrace(req,resp);
104 | } else {
105 | // 如果没有被请求到的话
106 | String errMsg = lStrings.getString("http.method_not_implemented");
107 | Object[] errArgs = new Object[1];
108 | errArgs[0] = method;
109 | errMsg = MessageFormat.format(errMsg, errArgs);
110 | // 501 HTTP状态码
111 | resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
112 | }
113 | }
114 |
115 | }
116 |
--------------------------------------------------------------------------------
/src/org/servlet/async/AsyncServlet.java:
--------------------------------------------------------------------------------
1 | package org.servlet.async;
2 |
3 | import java.io.IOException;
4 | import java.util.Date;
5 |
6 | import javax.servlet.AsyncContext;
7 | import javax.servlet.ServletException;
8 | import javax.servlet.annotation.WebServlet;
9 | import javax.servlet.http.HttpServlet;
10 | import javax.servlet.http.HttpServletRequest;
11 | import javax.servlet.http.HttpServletResponse;
12 | /*
13 | * Copyright [2015] [Jeff Lee]
14 | *
15 | * Licensed under the Apache License, Version 2.0 (the "License");
16 | * you may not use this file except in compliance with the License.
17 | * You may obtain a copy of the License at
18 | *
19 | * http://www.apache.org/licenses/LICENSE-2.0
20 | *
21 | * Unless required by applicable law or agreed to in writing, software
22 | * distributed under the License is distributed on an "AS IS" BASIS,
23 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24 | * See the License for the specific language governing permissions and
25 | * limitations under the License.
26 | */
27 |
28 | /**
29 | * @author Jeff Lee
30 | * @since 2015-9-3 20:30:19
31 | * Servlet 3.0提供的异步处理
32 | * 通过AsyncContext类实现,该对象从请求Request的startAsync方法获取。
33 | */
34 | @WebServlet(urlPatterns="/async",asyncSupported=true)// 开始异步调用
35 | public class AsyncServlet extends HttpServlet {
36 |
37 | private static final long serialVersionUID = -6795872120748178723L;
38 |
39 | @Override
40 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
41 | throws ServletException,IOException {
42 | resp.setContentType("text/html;charset=UTF-8");
43 | Date startDate = new Date();
44 | System.out.println("Servlet当前时间 --- " + startDate );
45 |
46 | // 从请求中获取AsyncContext
47 | AsyncContext asyncContext = req.startAsync();
48 | // 设置异步调用的超时时长
49 | asyncContext.setTimeout(30*1000);// 30秒
50 | // 开始异步调用
51 | asyncContext.start(new AsyncThread(asyncContext));
52 |
53 | Date endDate = new Date();
54 | System.out.println("Servlet结束时间 --- " + endDate);
55 |
56 | // startDate和endDate时间差不多相等。
57 | // 说明Servlet重新发起了一条线程去掉用耗时业务方法,避免了阻塞式调用
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/org/servlet/async/AsyncThread.java:
--------------------------------------------------------------------------------
1 | package org.servlet.async;
2 |
3 | import java.util.Date;
4 |
5 | import javax.servlet.AsyncContext;
6 | import javax.servlet.ServletRequest;
7 |
8 | /*
9 | * Copyright [2015] [Jeff Lee]
10 | *
11 | * Licensed under the Apache License, Version 2.0 (the "License");
12 | * you may not use this file except in compliance with the License.
13 | * You may obtain a copy of the License at
14 | *
15 | * http://www.apache.org/licenses/LICENSE-2.0
16 | *
17 | * Unless required by applicable law or agreed to in writing, software
18 | * distributed under the License is distributed on an "AS IS" BASIS,
19 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 | * See the License for the specific language governing permissions and
21 | * limitations under the License.
22 | */
23 |
24 | /**
25 | * @author Jeff Lee
26 | * @since 2015-9-3 20:30:19
27 | * Servlet 3.0提供的异步处理
28 | * 通过AsyncContext类实现,该对象从请求Request的startAsync方法获取。
29 | */
30 | public class AsyncThread implements Runnable {
31 |
32 | // 异步上下文
33 | private AsyncContext asyncContext = null;
34 |
35 | public AsyncThread(AsyncContext asyncContext) {
36 | this.asyncContext = asyncContext;
37 | }
38 |
39 | @Override
40 | public void run() {
41 | try {
42 | // 开始时间
43 | Date startDate = new Date();
44 | // 暂停5秒
45 | Thread.sleep(5 * 1000);
46 | // 开始时间
47 | Date endDate = new Date();
48 |
49 | // 从异步上下文获取请求对象
50 | ServletRequest request = asyncContext.getRequest();
51 | request.setAttribute("name", "BYSocket");
52 | request.setAttribute("startDate", startDate);
53 | request.setAttribute("endDate", endDate);
54 | asyncContext.dispatch("/async/asyncThread.jsp");
55 | } catch (InterruptedException e) {
56 | e.printStackTrace();
57 | }
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/org/servlet/reqAndresp/HelloWorldServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.reqAndresp;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.annotation.WebServlet;
8 | import javax.servlet.http.HttpServlet;
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | /*
12 | * Copyright [2015] [Jeff Lee]
13 | *
14 | * Licensed under the Apache License, Version 2.0 (the "License");
15 | * you may not use this file except in compliance with the License.
16 | * You may obtain a copy of the License at
17 | *
18 | * http://www.apache.org/licenses/LICENSE-2.0
19 | *
20 | * Unless required by applicable law or agreed to in writing, software
21 | * distributed under the License is distributed on an "AS IS" BASIS,
22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 | * See the License for the specific language governing permissions and
24 | * limitations under the License.
25 | */
26 |
27 | /**
28 | * @author Jeff Lee
29 | * @since 2015-6-25 19:46:45
30 | * HelloWrold案例
31 | */
32 | @WebServlet(urlPatterns = "/helloWorld.html")
33 | public class HelloWorldServletT extends HttpServlet{
34 |
35 | private static final long serialVersionUID = 1L;
36 |
37 | @Override
38 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
39 | throws ServletException, IOException{
40 | // 获取输出打印对象
41 | PrintWriter out = resp.getWriter();
42 | out.println("Hello,Servlet/JSP World!");
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/org/servlet/reqAndresp/LifeCircleServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.reqAndresp;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.annotation.WebServlet;
7 | import javax.servlet.http.HttpServlet;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 |
11 | /*
12 | * Copyright [2015] [Jeff Lee]
13 | *
14 | * Licensed under the Apache License, Version 2.0 (the "License");
15 | * you may not use this file except in compliance with the License.
16 | * You may obtain a copy of the License at
17 | *
18 | * http://www.apache.org/licenses/LICENSE-2.0
19 | *
20 | * Unless required by applicable law or agreed to in writing, software
21 | * distributed under the License is distributed on an "AS IS" BASIS,
22 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 | * See the License for the specific language governing permissions and
24 | * limitations under the License.
25 | */
26 |
27 | /**
28 | * @author Jeff Lee
29 | * @since 2015-7-10 21:40:41
30 | * Servlet生命周期演示案例
31 | */
32 | @WebServlet(urlPatterns = "/lifeCircle")
33 | public class LifeCircleServletT extends HttpServlet {
34 |
35 | private static final long serialVersionUID = 1L;
36 |
37 | @Override
38 | protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
39 | resp.setContentType("text/html;");
40 | resp.setCharacterEncoding("UTF-8");
41 | resp.setHeader("content-type","text/html;charset=UTF-8");
42 |
43 | System.out.println("Servlet 执行了。");
44 | resp.getWriter().println("Servlet生命周期案例。
Servlet 执行了!");
45 | }
46 |
47 | @Override
48 | public void destroy() {
49 | System.out.println("Servlet 被卸载了!");
50 | }
51 |
52 | @Override
53 | public void init() throws ServletException {
54 | System.out.println("Servlet 初始化了!\t(初始化只有一次,Servlet是单例的。)ps:不信可再次访问。");
55 | }
56 |
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/org/servlet/reqAndresp/SuperServiceServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.reqAndresp;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.annotation.WebServlet;
7 | import javax.servlet.http.HttpServlet;
8 | import javax.servlet.http.HttpServletRequest;
9 | import javax.servlet.http.HttpServletResponse;
10 | /*
11 | * Copyright [2015] [Jeff Lee]
12 | *
13 | * Licensed under the Apache License, Version 2.0 (the "License");
14 | * you may not use this file except in compliance with the License.
15 | * You may obtain a copy of the License at
16 | *
17 | * http://www.apache.org/licenses/LICENSE-2.0
18 | *
19 | * Unless required by applicable law or agreed to in writing, software
20 | * distributed under the License is distributed on an "AS IS" BASIS,
21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 | * See the License for the specific language governing permissions and
23 | * limitations under the License.
24 | */
25 |
26 | /**
27 | * @author Jeff Lee
28 | * @since 2015-7-10 23:11:57
29 | * super.service测试案例
30 | */
31 | @WebServlet("/superService")
32 | public class SuperServiceServletT extends HttpServlet {
33 |
34 | private static final long serialVersionUID = 1L;
35 |
36 | @Override
37 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
38 | throws ServletException, IOException {
39 | System.out.println("第三步:ServiceServletT.doGet()");
40 |
41 | resp.setContentType("text/html;");
42 | resp.setCharacterEncoding("UTF-8");
43 | resp.setHeader("content-type","text/html;charset=UTF-8");
44 |
45 | resp.getWriter().println("super.service测试案例");
46 | }
47 |
48 | @Override
49 | protected void service(HttpServletRequest req, HttpServletResponse resp)
50 | throws ServletException, IOException {
51 | System.out.println("第一步:ServiceServletT.service()");
52 | // 第二步:调用父类{@Link BaseServlet}的service方法
53 | super.service(req, resp);
54 | // 第三步:父类{@Link HttpServlet.doGet} 调用{@Link ServiceServletT.doGet}
55 | // 因为父类doGet被Override,如果调用父类doGet需要 super。doGet()
56 | }
57 |
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/src/org/servlet/sessionMngmt/HttpSessionByCookieServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.sessionMngmt;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.annotation.WebServlet;
8 | import javax.servlet.http.HttpServlet;
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | import javax.servlet.http.HttpSession;
12 | /*
13 | * Copyright [2015] [Jeff Lee]
14 | *
15 | * Licensed under the Apache License, Version 2.0 (the "License");
16 | * you may not use this file except in compliance with the License.
17 | * You may obtain a copy of the License at
18 | *
19 | * http://www.apache.org/licenses/LICENSE-2.0
20 | *
21 | * Unless required by applicable law or agreed to in writing, software
22 | * distributed under the License is distributed on an "AS IS" BASIS,
23 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24 | * See the License for the specific language governing permissions and
25 | * limitations under the License.
26 | */
27 |
28 | /**
29 | * @author Jeff Lee
30 | * @since 2015-7-12 10:58:28
31 | * HttpSession的默认Cookie实现案例
32 | */
33 | @WebServlet(urlPatterns = "/sessionByCookie")
34 | public class HttpSessionByCookieServletT extends HttpServlet {
35 |
36 | private static final long serialVersionUID = 1L;
37 |
38 | @Override
39 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
40 | throws ServletException, IOException {
41 |
42 | // 获取session
43 | // 如果是第一次请求的话,会创建一个HttpSeesion,等同于 req.getSession(true);
44 | // 如果已存在session,则会获取session。
45 | HttpSession session = req.getSession();
46 |
47 | if (session.isNew()) {
48 | // 设置session属性值
49 | session.setAttribute("name", "Jeff");
50 | }
51 | // 获取SessionId
52 | String sessionId = session.getId();
53 |
54 | PrintWriter out = resp.getWriter();
55 | // 如果HttpSeesion是新建的话
56 | if (session.isNew()) {
57 | out.println("Hello,HttpSession!
The first response - SeesionId="
58 | + sessionId + "
");
59 | } else {
60 | out.println("Hello,HttpSession!
The second response - SeesionId="
61 | + sessionId + "
");
62 | // 从Session获取属性值
63 | out.println("The second-response - name: "
64 | + session.getAttribute("name"));
65 | }
66 |
67 | }
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/src/org/servlet/sessionMngmt/HttpSessionMethodsServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.sessionMngmt;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.annotation.WebServlet;
8 | import javax.servlet.http.HttpServlet;
9 | import javax.servlet.http.HttpServletRequest;
10 | import javax.servlet.http.HttpServletResponse;
11 | import javax.servlet.http.HttpSession;
12 |
13 | /*
14 | * Copyright [2015] [Jeff Lee]
15 | *
16 | * Licensed under the Apache License, Version 2.0 (the "License");
17 | * you may not use this file except in compliance with the License.
18 | * You may obtain a copy of the License at
19 | *
20 | * http://www.apache.org/licenses/LICENSE-2.0
21 | *
22 | * Unless required by applicable law or agreed to in writing, software
23 | * distributed under the License is distributed on an "AS IS" BASIS,
24 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 | * See the License for the specific language governing permissions and
26 | * limitations under the License.
27 | */
28 |
29 | /**
30 | * @author Jeff Lee
31 | * @since 2015-6-25 19:46:45
32 | * HttpSession的详细案例
33 | */
34 | @WebServlet(urlPatterns = "/sessionMethods")
35 | public class HttpSessionMethodsServletT extends HttpServlet{
36 |
37 | private static final long serialVersionUID = 1L;
38 |
39 | @Override
40 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
41 | throws ServletException, IOException {
42 | resp.setContentType("text/html;");
43 | resp.setCharacterEncoding("UTF-8");
44 | resp.setHeader("content-type","text/html;charset=UTF-8");
45 | PrintWriter out = resp.getWriter();
46 |
47 | // 从请求中获取Session
48 | HttpSession session = req.getSession();
49 | // 绑定对象到Session
50 | session.setAttribute("sessionName", "sessionValue");
51 |
52 | // 返回第一次创建Session的时间
53 | out.println("创建会话时间:" + session.getCreationTime() + "
");
54 | // 返回离最近一次会话操作的间隔
55 | out.println("离最近一次会话操作的间隔:" + session.getLastAccessedTime() + "
");
56 | // 设置会话最大时间间隔
57 | session.setMaxInactiveInterval(10 * 60); // 10分钟,默认20分钟
58 | // 返回会话最大时间间隔
59 | out.println("会话最大时间间隔:" + session.getMaxInactiveInterval() + "
");
60 |
61 | // 结束会话
62 | //session.invalidate();
63 | //session.setMaxInactiveInterval(0);
64 | }
65 |
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/org/servlet/sessionMngmt/HttpSessionServletT.java:
--------------------------------------------------------------------------------
1 | package org.servlet.sessionMngmt;
2 |
3 | import java.io.IOException;
4 | import java.io.PrintWriter;
5 |
6 | import javax.servlet.ServletException;
7 | import javax.servlet.annotation.WebServlet;
8 | import javax.servlet.http.HttpServlet;
9 | /*
10 | * Copyright [2015] [Jeff Lee]
11 | *
12 | * Licensed under the Apache License, Version 2.0 (the "License");
13 | * you may not use this file except in compliance with the License.
14 | * You may obtain a copy of the License at
15 | *
16 | * http://www.apache.org/licenses/LICENSE-2.0
17 | *
18 | * Unless required by applicable law or agreed to in writing, software
19 | * distributed under the License is distributed on an "AS IS" BASIS,
20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 | * See the License for the specific language governing permissions and
22 | * limitations under the License.
23 | */
24 | import javax.servlet.http.HttpServletRequest;
25 | import javax.servlet.http.HttpServletResponse;
26 | import javax.servlet.http.HttpSession;
27 | /*
28 | * Copyright [2015] [Jeff Lee]
29 | *
30 | * Licensed under the Apache License, Version 2.0 (the "License");
31 | * you may not use this file except in compliance with the License.
32 | * You may obtain a copy of the License at
33 | *
34 | * http://www.apache.org/licenses/LICENSE-2.0
35 | *
36 | * Unless required by applicable law or agreed to in writing, software
37 | * distributed under the License is distributed on an "AS IS" BASIS,
38 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
39 | * See the License for the specific language governing permissions and
40 | * limitations under the License.
41 | */
42 |
43 | /**
44 | * @author Jeff Lee
45 | * @since 2015-6-25 19:46:45
46 | * HttpSession的简单案例
47 | */
48 | @WebServlet(urlPatterns = "/session")
49 | public class HttpSessionServletT extends HttpServlet{
50 |
51 | private static final long serialVersionUID = 1L;
52 |
53 | @Override
54 | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
55 | throws ServletException, IOException {
56 | // 从请求中获取Session
57 | HttpSession session = req.getSession();
58 | // 绑定对象到Session
59 | session.setAttribute("sessionName", "sessionValue");
60 |
61 | PrintWriter out = resp.getWriter();
62 | out.println("Hello,HttpSession!SeesionId" + session.getId() + "
");
63 | // 从Session获取对象
64 | out.println("sessionName: " + session.getAttribute("sessionName"));
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/org/tomcat/jsp/jasper/JspCompilerT.java:
--------------------------------------------------------------------------------
1 | package org.tomcat.jsp.jasper;
2 |
3 | import org.apache.jasper.JspC;
4 |
5 | /*
6 | * Copyright [2015] [Jeff Lee]
7 | *
8 | * Licensed under the Apache License, Version 2.0 (the "License");
9 | * you may not use this file except in compliance with the License.
10 | * You may obtain a copy of the License at
11 | *
12 | * http://www.apache.org/licenses/LICENSE-2.0
13 | *
14 | * Unless required by applicable law or agreed to in writing, software
15 | * distributed under the License is distributed on an "AS IS" BASIS,
16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 | * See the License for the specific language governing permissions and
18 | * limitations under the License.
19 | */
20 |
21 | /**
22 | * @author Jeff Lee
23 | * @since 2015-7-16 13:32:04
24 | * Jasper引擎编译JSP
25 | * jar:Ant相关 + tomcat-juli.jar
26 | */
27 | public class JspCompilerT {
28 |
29 | /**
30 | * 编译Jsp文件,并输出
31 | * @param uriRoot web应用的root目录
32 | * @param outPutDir .java和.class文件输出目录
33 | * @param jspFileName 要编译的jsp
34 | * @return
35 | */
36 | public static String jspCompiler(
37 | String uriRoot,
38 | String outPutDir,
39 | String jspFileName){
40 | String errorMsg = "";
41 | try {
42 | // 创建一个Jsp编译器
43 | JspC jspC = new JspC();
44 |
45 | // 设置相关属性,参加方法
46 | jspC.setUriroot(uriRoot);
47 | jspC.setOutputDir(outPutDir);
48 | jspC.setJspFiles(jspFileName);
49 |
50 | // 是否编译,是会包含.class文件
51 | jspC.setCompile(true);
52 | jspC.execute();
53 | } catch (Exception e) {
54 | errorMsg = e.toString();
55 | }
56 | return errorMsg;
57 | }
58 |
59 | public static void main(String[] args) {
60 | System.out.println(
61 | JspCompilerT.jspCompiler(
62 | "./WebContent",
63 | "E:/",
64 | "jspC.jsp")// 文件目标:WebContent/jspC.jsp
65 | );
66 | }
67 | }
68 |
--------------------------------------------------------------------------------