几个实用的Servlet应用例子-入门、cookie、session及上传文件
1Servlet可以被认为是服务端的applet,它被WEB服务器加载和执行,前端可以显示页面和获得页面数据,后台可以操纵数据库,能完成JavaBean的很多功能。在这里我较为详细的说说Servlet在Cookie,Session和上传文件上的应用,在说明时我给出一些能编绎运行的小例子,最后给出一个文件上传例子以加深印象。
2 我们先来看看SERVLET程序的基本构架:
3式1:
4 package test;
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9 public class test extends HttpServlet {
10 public void init(ServletConfig config) throws ServletException {
11 super.init(config);
12}
13 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14 int f =1; switch(f){
15 case 1:firstMothed(request,respponse);break;
16}
17}
18 public void firstMothed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 response.setContentType("text/html");
20 OutputStreamWriter osw = new
21 OutputStreamWriter(response.getOutputStream());
22 PrintWriter out = new PrintWriter (response.getOutputStream());
23 out.println("< html>");
24 out.println("< head>< title>Servlet1< /title>< /head>");
25 out.println("< body>你好!");
26 out.println("< /body>< /html>");
27 out.close();
28}
29}
30式2:
31 package test;
32 import javax.servlet.*;
33 import javax.servlet.http.*;
34 import java.io.*;
35 import java.util.*;
36 public class test extends HttpServlet {
37 public void init(ServletConfig config) throws ServletException {
38 super.init(config);
39}
40 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
41 response.setContentType("text/html");
42 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
43 PrintWriter out = new PrintWriter (response.getOutputStream());
44 out.println("< html>");
45 out.println("< head>< title>Servlet1< /title>< /head>");
46 out.println("< body>你好!");
47 out.println("< /body>< /html>");
48 out.close();
49}
50 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
51 response.setContentType("text/html");
52 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
53 PrintWriter out = new PrintWriter (response.getOutputStream());
54 out.println("< html>");
55 out.println("< head>< title>Servlet1< /title>< /head>");
56 out.println("< body>你好!");
57 out.println("< /body>< /html>");
58 out.close();
59}
60}
61 式1适合于作总控模块,此SERVLET作中间调度,根据不同的f值调用不同的SERVLET或方法。
62式2适合于对html的get和post有不同要求的情况。
63 但这并不是绝对的,式2就完全可以代替式1,只要在doGet()方法中写上doPost就与式1完全一样。
64在init方法中执行的语句,只要这个servlet被启动了就一直有效,比如,我们在init()中new了一个对象,那么这个对象的内存空间就永远存在,除非显式地把这个对象赋为null,或重启服务。
65 HttpServletRequest和HttpServletResponse两个对象实现http请求,它们有很多有用的方法,在下面的cookie和session管理中会细加描述。
66 1, cookie管理 cookie用于在客户端保存个人所特有的信息,它采取在客户机写临时文件的机制。
67 package test;
68 import javax.servlet.*;
69 import javax.servlet.http.*;
70 import java.io.*;
71 import java.util.*;
72 public class test extends HttpServlet {
73 public void init(ServletConfig config) throws ServletException {
74 super.init(config);
75}
76 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
77 //写cookie
78 String CookieName ="js79"; //若是汉字则需编码
79 String CookieValue = "yesky";//若是汉字则需编码
80 Cookie cookie = new Cookie(CookieName,CookieValue);
81 cookie.setMaxAge(age); // age = Integer.MAX_VALUE 永不过期
82 cookie.setPath("/");
83 //读cookie
84 String value = null;
85 Cookie[] cookies = request.getCookies();
86 if (cookies != null) {
87 for (int i=0; i< cookies.length; i++) {
88 if (cookies[i].getName().equals(CookieName))
89 value = cookies[i].getValue();
90 break;
91}
92}
93}
94 response.setContentType("text/html");
95 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
96 PrintWriter out = new PrintWriter (response.getOutputStream());
97 out.println("< html>");
98 out.println("< head>< title>test< /title>< /head>");
99 out.println("cookie键:"+CookieName+"< br>");
100 out.println("cookie值: "+value);
101 out.println("< /body>< /html>");
102 out.close();
103}
104}
105 2,session管理
106 Session在Servlet中是很有用的,它比cookie安全可靠灵活,但是管理起来有点麻烦,用得不好会造成服务器的开销很大,浪费资源。下面是一个基于Session管理一个对象的简单例子。
107一个简单的bean对象TestObject
108 package test;
109 public class TestObject extends Object {
110 int id = 0; public String cur="";
111}
112 package test;
113 import javax.servlet.*;
114 import javax.servlet.http.*;
115 import java.io.*;
116 import java.util.*;
117 public class TestMan extends HttpServlet {
118 public void init(ServletConfig config) throws ServletException {
119 super.init(config);
120}
121 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
122 int f = 1;
123 if(request.getParameter("f")!=null)
124 f =
125 Integer.parseInt(request.getParameter("f"));
126 switch(f){
127 case 1: this.getResult(request,response);
128 break;
129 case 2:
130 this.setSession(request,response);
131 break;
132}
133}
134 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
135 doGet(request,response);
136}
137 public void getResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
138 TestObject testObject = null;
139 testObject = getStatus(request,response);
140 String html = testObject.id; doWrite( response,html);
141}
142 public void setSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
143 HttpSession session = request.getSession();
144 TestObject testObject = null;
145 testObject = getStatus(request,response);
146 String tmp = null;
147 tmp = request.getParameter("id");
148 if(tmp != null) testObject.id = tmp;
149 session.putValue("testObject ",article);
150 getResult(request,response);
151}
152 private TestObject getStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
153 HttpSession session = request.getSession();
154 TestObject testObject = null;
155 if(session!=null){
156 if(session.getValue("testObject ")!=null){
157 testObject = (TestObject)session.getValue("testObject ");
158}
159 else{
160 testObject = new TestObject ();
161}
162}
163 else{
164 testObject = new TestObject ();
165}
166 return testObject;
167}
168 private void doWrite(HttpServletResponse response,String html) throws ServletException, IOException {
169 PrintWriter out = response.getWriter();
170 out.println(html);
171 out.close();
172}
173 /////////////////////////////////////////////////////////
174}
175 若能轻松搞定上面的例子,相信读者对SERVLET已有了较为深刻的理解。
176下面再介绍一个上传文件例子,其中汲及到了下载的免费JavaBean (如有感兴趣的朋友,可来函索要免费JavaBean源代码,Email:js79@yesky.com)
177 上传基本原理:由页面发出一个http请求,服务端得到请求后,解析多媒体协议,读出文件内容,写文件内容到服务器,所有的这些功能都封装到JavaBean中。
178 上传文件的必需条件:Browser端< form>表单的ENCTYPE属性值必须为 multipart/form-data,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,< input>的type属性必须是file。
179 package upload;
180 import javax.servlet.*;
181 import javax.servlet.http.*;
182 import java.io.*;
183 import java.util.*;
184 public class UpLoadServlet extends HttpServlet {
185 public void init(ServletConfig config) throws ServletException{
186 super.init(config);
187}
188 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
189 PrintWriter out = response.getWriter();
190 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
191 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
192 +"< /HEAD>"
193 +"< body>");
194 out.println("< div align=´center´ valign=´top´>"
195 +"< span class=´nava´>请你选择上传的文件(请注意文件大小只能在20K之内)< /span>< BR>"
196 +"< form ENCTYPE=´multipart/form-data´ method=post action=´´>"
197 +"< input type=´file´ name=´file´>"
198 +"< input type=´submit´ value=´发送´>"
199 +"< /form>"
200 +"< /div>");
201 out.println("< /body>< /html>");
202 out.close();
203}
204 ////////
205 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
206 PrintWriter out = response.getWriter();
207 int tmpID = 1; try {
208 MultipartRequest multi = new MultipartRequest(request,"/home/js79/html/", 5 * 1024 * 1024);
209}
210 catch(Exception e){
211 tmpID = -1; System.out.println(e);
212}
213 if(tmpID == 1){
214 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
215 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
216 +"< /HEAD>"
217 +"< body>");
218 out.println("上传成功!< /body>< /html>");
219}
220 else{
221 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
222 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
223 +"< /HEAD>"
224 +"< body>");
225 out.println("上传不成功!< /body>< /html>");
226}
227 out.close();
228}
229}
2 我们先来看看SERVLET程序的基本构架:
3式1:
4 package test;
5 import javax.servlet.*;
6 import javax.servlet.http.*;
7 import java.io.*;
8 import java.util.*;
9 public class test extends HttpServlet {
10 public void init(ServletConfig config) throws ServletException {
11 super.init(config);
12}
13 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
14 int f =1; switch(f){
15 case 1:firstMothed(request,respponse);break;
16}
17}
18 public void firstMothed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 response.setContentType("text/html");
20 OutputStreamWriter osw = new
21 OutputStreamWriter(response.getOutputStream());
22 PrintWriter out = new PrintWriter (response.getOutputStream());
23 out.println("< html>");
24 out.println("< head>< title>Servlet1< /title>< /head>");
25 out.println("< body>你好!");
26 out.println("< /body>< /html>");
27 out.close();
28}
29}
30式2:
31 package test;
32 import javax.servlet.*;
33 import javax.servlet.http.*;
34 import java.io.*;
35 import java.util.*;
36 public class test extends HttpServlet {
37 public void init(ServletConfig config) throws ServletException {
38 super.init(config);
39}
40 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
41 response.setContentType("text/html");
42 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
43 PrintWriter out = new PrintWriter (response.getOutputStream());
44 out.println("< html>");
45 out.println("< head>< title>Servlet1< /title>< /head>");
46 out.println("< body>你好!");
47 out.println("< /body>< /html>");
48 out.close();
49}
50 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
51 response.setContentType("text/html");
52 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
53 PrintWriter out = new PrintWriter (response.getOutputStream());
54 out.println("< html>");
55 out.println("< head>< title>Servlet1< /title>< /head>");
56 out.println("< body>你好!");
57 out.println("< /body>< /html>");
58 out.close();
59}
60}
61 式1适合于作总控模块,此SERVLET作中间调度,根据不同的f值调用不同的SERVLET或方法。
62式2适合于对html的get和post有不同要求的情况。
63 但这并不是绝对的,式2就完全可以代替式1,只要在doGet()方法中写上doPost就与式1完全一样。
64在init方法中执行的语句,只要这个servlet被启动了就一直有效,比如,我们在init()中new了一个对象,那么这个对象的内存空间就永远存在,除非显式地把这个对象赋为null,或重启服务。
65 HttpServletRequest和HttpServletResponse两个对象实现http请求,它们有很多有用的方法,在下面的cookie和session管理中会细加描述。
66 1, cookie管理 cookie用于在客户端保存个人所特有的信息,它采取在客户机写临时文件的机制。
67 package test;
68 import javax.servlet.*;
69 import javax.servlet.http.*;
70 import java.io.*;
71 import java.util.*;
72 public class test extends HttpServlet {
73 public void init(ServletConfig config) throws ServletException {
74 super.init(config);
75}
76 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
77 //写cookie
78 String CookieName ="js79"; //若是汉字则需编码
79 String CookieValue = "yesky";//若是汉字则需编码
80 Cookie cookie = new Cookie(CookieName,CookieValue);
81 cookie.setMaxAge(age); // age = Integer.MAX_VALUE 永不过期
82 cookie.setPath("/");
83 //读cookie
84 String value = null;
85 Cookie[] cookies = request.getCookies();
86 if (cookies != null) {
87 for (int i=0; i< cookies.length; i++) {
88 if (cookies[i].getName().equals(CookieName))
89 value = cookies[i].getValue();
90 break;
91}
92}
93}
94 response.setContentType("text/html");
95 OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
96 PrintWriter out = new PrintWriter (response.getOutputStream());
97 out.println("< html>");
98 out.println("< head>< title>test< /title>< /head>");
99 out.println("cookie键:"+CookieName+"< br>");
100 out.println("cookie值: "+value);
101 out.println("< /body>< /html>");
102 out.close();
103}
104}
105 2,session管理
106 Session在Servlet中是很有用的,它比cookie安全可靠灵活,但是管理起来有点麻烦,用得不好会造成服务器的开销很大,浪费资源。下面是一个基于Session管理一个对象的简单例子。
107一个简单的bean对象TestObject
108 package test;
109 public class TestObject extends Object {
110 int id = 0; public String cur="";
111}
112 package test;
113 import javax.servlet.*;
114 import javax.servlet.http.*;
115 import java.io.*;
116 import java.util.*;
117 public class TestMan extends HttpServlet {
118 public void init(ServletConfig config) throws ServletException {
119 super.init(config);
120}
121 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
122 int f = 1;
123 if(request.getParameter("f")!=null)
124 f =
125 Integer.parseInt(request.getParameter("f"));
126 switch(f){
127 case 1: this.getResult(request,response);
128 break;
129 case 2:
130 this.setSession(request,response);
131 break;
132}
133}
134 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
135 doGet(request,response);
136}
137 public void getResult(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
138 TestObject testObject = null;
139 testObject = getStatus(request,response);
140 String html = testObject.id; doWrite( response,html);
141}
142 public void setSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
143 HttpSession session = request.getSession();
144 TestObject testObject = null;
145 testObject = getStatus(request,response);
146 String tmp = null;
147 tmp = request.getParameter("id");
148 if(tmp != null) testObject.id = tmp;
149 session.putValue("testObject ",article);
150 getResult(request,response);
151}
152 private TestObject getStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
153 HttpSession session = request.getSession();
154 TestObject testObject = null;
155 if(session!=null){
156 if(session.getValue("testObject ")!=null){
157 testObject = (TestObject)session.getValue("testObject ");
158}
159 else{
160 testObject = new TestObject ();
161}
162}
163 else{
164 testObject = new TestObject ();
165}
166 return testObject;
167}
168 private void doWrite(HttpServletResponse response,String html) throws ServletException, IOException {
169 PrintWriter out = response.getWriter();
170 out.println(html);
171 out.close();
172}
173 /////////////////////////////////////////////////////////
174}
175 若能轻松搞定上面的例子,相信读者对SERVLET已有了较为深刻的理解。
176下面再介绍一个上传文件例子,其中汲及到了下载的免费JavaBean (如有感兴趣的朋友,可来函索要免费JavaBean源代码,Email:js79@yesky.com)
177 上传基本原理:由页面发出一个http请求,服务端得到请求后,解析多媒体协议,读出文件内容,写文件内容到服务器,所有的这些功能都封装到JavaBean中。
178 上传文件的必需条件:Browser端< form>表单的ENCTYPE属性值必须为 multipart/form-data,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,< input>的type属性必须是file。
179 package upload;
180 import javax.servlet.*;
181 import javax.servlet.http.*;
182 import java.io.*;
183 import java.util.*;
184 public class UpLoadServlet extends HttpServlet {
185 public void init(ServletConfig config) throws ServletException{
186 super.init(config);
187}
188 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
189 PrintWriter out = response.getWriter();
190 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
191 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
192 +"< /HEAD>"
193 +"< body>");
194 out.println("< div align=´center´ valign=´top´>"
195 +"< span class=´nava´>请你选择上传的文件(请注意文件大小只能在20K之内)< /span>< BR>"
196 +"< form ENCTYPE=´multipart/form-data´ method=post action=´´>"
197 +"< input type=´file´ name=´file´>"
198 +"< input type=´submit´ value=´发送´>"
199 +"< /form>"
200 +"< /div>");
201 out.println("< /body>< /html>");
202 out.close();
203}
204 ////////
205 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
206 PrintWriter out = response.getWriter();
207 int tmpID = 1; try {
208 MultipartRequest multi = new MultipartRequest(request,"/home/js79/html/", 5 * 1024 * 1024);
209}
210 catch(Exception e){
211 tmpID = -1; System.out.println(e);
212}
213 if(tmpID == 1){
214 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
215 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
216 +"< /HEAD>"
217 +"< body>");
218 out.println("上传成功!< /body>< /html>");
219}
220 else{
221 out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
222 +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
223 +"< /HEAD>"
224 +"< body>");
225 out.println("上传不成功!< /body>< /html>");
226}
227 out.close();
228}
229}