📄 53.html
字号:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="description" content="Java,JDBC,EJB,Open Source,jdk,rmi">
<meta name="Keywords"
content="Java, servlets, Java servlet, Javascript, ActiveX, VRML,
applet, applets, directory, news, jdbc, applications,
Java applications, Java developer, Java development, developer,
classes, Jars.com, Jars, intranet, Java applet, Javabeans,
Java products, JDK, Java development kit, java development environment, JIT,
JavaPlan, enterprise tools, JVM, Java Virtual Machine, Java resources,
SUN, CGI, Perl, database, network, html,
xml, dhtml, rating, ratings, review, jars, cgi, programming,
software review, software rating">
<title>csdn_几个实用的Servlet应用例子---入门、cookie、session及上传文件</title>
<style>
.news { BACKGROUND: #007cd3; font-family: "宋体"; font-size: 9pt }
.t { font-family: "宋体"; font-size: 9pt }
.t1 { color:#007cd3; font-family: "宋体"; font-size: 9pt }
.white { font-family: "宋体"; font-size: 9pt;color:#FFFFFF }
.red { font-family: "宋体"; font-size: 9pt;color:#FF0000 }
A:visited {color:#0000FF}
A:hover {color: #ff6666; text-decoration: none}
.text {font-size: 12px; line-height: 160%; font-family: "宋体"}
.text1 {color:#000000; font-size: 12px; line-height: 130%; font-family: "宋体"; text-decoration: none}
.text1:visited {color:#000000}
.text1:hover {color: #000000}
.text2 {color:#000000; font-size: 12px; line-height: 130%; font-family: "宋体"; text-decoration: none}
.text2:visited {color:#000000}
.text2:hover {color: #000000}
.text3 {font-size: 12px; line-height: 100%; font-family: "宋体"; text-decoration: none}
.large {font-size: 14.8px; line-height: 130%}
</style>
</head>
<body
<center>
<tr>
<td WIDTH="100%" VALIGN="TOP">
<tr>
<td WIDTH="100%" CLASS="white"></td>
</tr>
<tr>
<td WIDTH="50%" bordercolor="#FFFFFF" CLASS="t1" bgcolor="#F0F0F0" align="center" nowrap>几个实用的Servlet应用例子---入门、cookie、session及上传文件</td>
</tr>
<tr> <td WIDTH="100%" bordercolor="#FFFFFF" CLASS="t" bgcolor="#F0F0F0" colspan="2">
<P
class=MsoNormal><BR> Servlet可以被认为是服务端的applet,它被WEB服务器加载和执行,前端可以显示页面和获得页面数据,后台可以操纵数据库,能完成JavaBean的很多功能。在这里我较为详细的说说Servlet在Cookie,Session和上传文件上的应用,在说明时我给出一些能编绎运行的小例子,最后给出一个文件上传例子以加深印象。
<BR> 我们先来看看SERVLET程序的基本构架: <BR>式1:<BR> package test;<BR> import
javax.servlet.*; <BR> import javax.servlet.http.*; <BR> import
java.io.*; <BR> import java.util.*; <BR> public class test extends
HttpServlet { <BR> public void init(ServletConfig config) throws
ServletException { <BR> super.init(config);<BR>} <BR> public void
service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { <BR> int f =1; switch(f){ <BR> case
1:firstMothed(request,respponse);break; <BR>} <BR>}<BR> public void
firstMothed(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
<BR> response.setContentType("text/html");<BR> OutputStreamWriter osw =
new <BR> OutputStreamWriter(response.getOutputStream());
<BR> PrintWriter out = new PrintWriter
(response.getOutputStream());<BR> out.println("< html>");
<BR> out.println("< head>< title>Servlet1< /title><
/head>");<BR> out.println("< body>你好!"); <BR> out.println("<
/body>< /html>"); <BR> out.close(); <BR>} <BR>}
<BR>式2:<BR> package test; <BR> import javax.servlet.*; <BR> import
javax.servlet.http.*;<BR> import java.io.*; <BR> import java.util.*;
<BR> public class test extends HttpServlet { <BR> public void
init(ServletConfig config) throws ServletException
{<BR> super.init(config);<BR>}<BR> public void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException,
IOException
{<BR> response.setContentType("text/html");<BR> OutputStreamWriter osw =
new OutputStreamWriter(response.getOutputStream());<BR> PrintWriter out =
new PrintWriter (response.getOutputStream());<BR> out.println("<
html>"); <BR> out.println("< head>< title>Servlet1<
/title>< /head>"); <BR> out.println("<
body>你好!");<BR> out.println("< /body><
/html>");<BR> out.close();<BR>}<BR> public void
doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{<BR> response.setContentType("text/html");<BR> OutputStreamWriter osw =
new OutputStreamWriter(response.getOutputStream()); <BR> PrintWriter out
= new PrintWriter (response.getOutputStream()); <BR> out.println("<
html>");<BR> out.println("< head>< title>Servlet1<
/title>< /head>"); <BR> out.println("< body>你好!");
<BR> out.println("< /body>< /html>"); <BR> out.close();
<BR>} <BR>} <BR> 式1适合于作总控模块,此SERVLET作中间调度,根据不同的f值调用不同的SERVLET或方法。
<BR>式2适合于对html的get和post有不同要求的情况。<BR> 但这并不是绝对的,式2就完全可以代替式1,只要在doGet()方法中写上doPost就与式1完全一样。<BR>在init方法中执行的语句,只要这个servlet被启动了就一直有效,比如,我们在init()中new了一个对象,那么这个对象的内存空间就永远存在,除非显式地把这个对象赋为null,或重启服务。<BR> HttpServletRequest和HttpServletResponse两个对象实现http请求,它们有很多有用的方法,在下面的cookie和session管理中会细加描述。<BR> 1,
cookie管理 cookie用于在客户端保存个人所特有的信息,它采取在客户机写临时文件的机制。 <BR> package test;
<BR> import javax.servlet.*; <BR> import javax.servlet.http.*;
<BR> import java.io.*; <BR> import java.util.*; <BR> public class test
extends HttpServlet {<BR> public void init(ServletConfig config) throws
ServletException {<BR> super.init(config);<BR>}<BR> public void
service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {<BR> //写cookie <BR> String CookieName
="js79"; //若是汉字则需编码 <BR> String CookieValue = "yesky";//若是汉字则需编码
<BR> Cookie cookie = new Cookie(CookieName,CookieValue);
<BR> cookie.setMaxAge(age); // age = Integer.MAX_VALUE
永不过期<BR> cookie.setPath("/");<BR> //读cookie <BR> String value =
null;<BR> Cookie[] cookies = request.getCookies();<BR> if (cookies !=
null) {<BR> for (int i=0; i< cookies.length; i++) { <BR> if
(cookies[i].getName().equals(CookieName))<BR> value =
cookies[i].getValue(); <BR> break; <BR>}
<BR>}<BR>}<BR> response.setContentType("text/html");
<BR> OutputStreamWriter osw = new
OutputStreamWriter(response.getOutputStream());<BR> PrintWriter out = new
PrintWriter (response.getOutputStream());<BR> out.println("<
html>");<BR> out.println("< head>< title>test<
/title>< /head>"); <BR> out.println("cookie键:"+CookieName+"<
br>"); <BR> out.println("cookie值: "+value); <BR> out.println("<
/body>< /html>");<BR> out.close();<BR>}<BR>}<BR> 2,session管理
<BR> Session在Servlet中是很有用的,它比cookie安全可靠灵活,但是管理起来有点麻烦,用得不好会造成服务器的开销很大,浪费资源。下面是一个基于Session管理一个对象的简单例子。
<BR>一个简单的bean对象TestObject<BR> package test; <BR> public class TestObject
extends Object {<BR> int id = 0; public String cur="";<BR>} <BR> package
test;<BR> import javax.servlet.*; <BR> import javax.servlet.http.*;
<BR> import java.io.*; <BR> import java.util.*;<BR> public class
TestMan extends HttpServlet { <BR> public void init(ServletConfig config)
throws ServletException {<BR> super.init(config);<BR>}<BR> public void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { <BR> int f =
1;<BR> if(request.getParameter("f")!=null)<BR> f =
<BR> Integer.parseInt(request.getParameter("f")); <BR> switch(f){
<BR> case 1: this.getResult(request,response); <BR> break;<BR> case
2:<BR> this.setSession(request,response);<BR> break; <BR>} <BR>}
<BR> public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
<BR> doGet(request,response);<BR>}<BR> public void
getResult(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {<BR> TestObject testObject =
null;<BR> testObject = getStatus(request,response);<BR> String html =
testObject.id; doWrite( response,html); <BR>}<BR> public void
setSession(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {<BR> HttpSession session =
request.getSession(); <BR> TestObject testObject = null; <BR> testObject
= getStatus(request,response); <BR> String tmp = null; <BR> tmp =
request.getParameter("id");<BR> if(tmp != null) testObject.id = tmp;
<BR> session.putValue("testObject ",article);
<BR> getResult(request,response);<BR>} <BR> private TestObject
getStatus(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {<BR> HttpSession session =
request.getSession(); <BR> TestObject testObject = null;
<BR> if(session!=null){<BR> if(session.getValue("testObject
")!=null){<BR> testObject = (TestObject)session.getValue("testObject
");<BR>} <BR> else{<BR> testObject = new TestObject
();<BR>}<BR>}<BR> else{ <BR> testObject = new TestObject ();
<BR>}<BR> return testObject; <BR>}<BR> private void
doWrite(HttpServletResponse response,String html) throws
ServletException, IOException { <BR> PrintWriter out =
response.getWriter();<BR> out.println(html);
<BR> out.close();<BR>}<BR> /////////////////////////////////////////////////////////
<BR>} <BR> 若能轻松搞定上面的例子,相信读者对SERVLET已有了较为深刻的理解。
<BR>下面再介绍一个上传文件例子,其中汲及到了下载的免费JavaBean
(如有感兴趣的朋友,可来函索要免费JavaBean源代码,Email:js79@yesky.com)
<BR> 上传基本原理:由页面发出一个http请求,服务端得到请求后,解析多媒体协议,读出文件内容,写文件内容到服务器,所有的这些功能都封装到JavaBean中。<BR> 上传文件的必需条件:Browser端<
form>表单的ENCTYPE属性值必须为
multipart/form-data,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,<
input>的type属性必须是file。 <BR> package upload;<BR> import
javax.servlet.*; <BR> import javax.servlet.http.*; <BR> import
java.io.*; <BR> import java.util.*; <BR> public class UpLoadServlet
extends HttpServlet {<BR> public void init(ServletConfig config) throws
ServletException{ <BR> super.init(config);<BR>} <BR> public void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {<BR> PrintWriter out =
response.getWriter();<BR> out.println("< HTML>< HEAD><
TITLE>UpLoad< /TITLE>"<BR> +"< meta http-equiv='Content-Type'
content='text/html; charset=gb2312'>" <BR> +"< /HEAD>"
<BR> +"< body>"); <BR> out.println("< div align='center'
valign='top'>"<BR> +"< span
class='nava'>请你选择上传的文件(请注意文件大小只能在20K之内)< /span>< BR>"
<BR> +"< form ENCTYPE='multipart/form-data' method=post action=''>"
<BR> +"< input type='file' name='file'>" <BR> +"< input
type='submit' value='发送'>" <BR> +"< /form>"<BR> +"<
/div>"); <BR> out.println("< /body><
/html>");<BR> out.close(); <BR>} <BR> ////////<BR> public void
doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {<BR> PrintWriter out =
response.getWriter(); <BR> int tmpID = 1; try {<BR> MultipartRequest
multi = new MultipartRequest(request,"/home/js79/html/", 5 * 1024 *
1024);<BR>}<BR> catch(Exception e){<BR> tmpID = -1;
System.out.println(e);<BR>} <BR> if(tmpID == 1){<BR> out.println("<
HTML>< HEAD>< TITLE>UpLoad< /TITLE>" <BR> +"<
meta http-equiv='Content-Type' content='text/html;
charset=gb2312'>"<BR> +"< /HEAD>"<BR> +"< body>");
<BR> out.println("上传成功!< /body>< /html>"); <BR>}
<BR> else{<BR> out.println("< HTML>< HEAD><
TITLE>UpLoad< /TITLE>"<BR> +"< meta http-equiv='Content-Type'
content='text/html; charset=gb2312'>" <BR> +"<
/HEAD>"<BR> +"< body>");<BR> out.println("上传不成功!<
/body>< /html>");<BR>} <BR> out.close();<BR>}<BR>} </P>
</td>
</tr>
</td>
</tr>
</div>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -