开发学院WEB开发Jsp 几个实用的Servlet应用例子-入门、cookie、sessio... 阅读

几个实用的Servlet应用例子-入门、cookie、session及上传文件

 2008-01-05 08:45:33 来源:WEB开发网   
核心提示:Servlet可以被认为是服务端的applet,它被WEB服务器加载和执行,几个实用的Servlet应用例子-入门、cookie、session及上传文件,前端可以显示页面和获得页面数据,后台可以操纵数据库,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,能完成javaBean的很多功能,在这里我较

  Servlet可以被认为是服务端的applet,它被WEB服务器加载和执行,前端可以显示页面和获得页面数据,后台可以操纵数据库,能完成javaBean的很多功能。在这里我较为具体的说说Servlet在Cookie,session和上传文件上的应用,在说明时我给出一些能编绎运行的小例子,最后给出一个文件上传例子以加深印象。
  我们先来看看SERVLET程序的基本构架:
式1:
  package test;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  public class test extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
  super.init(config);
}
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  int f =1; switch(f){
  case 1:firstMothed(request,respponse);break;
}
}
  public void firstMothed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/Html");
  OutputStreamWriter osw = new
  OutputStreamWriter(response.getOutputStream());
  PRintWriter out = new PrintWriter (response.getOutputStream());
  out.println("< html>");
  out.println("< head>< title>Servlet1< /title>< /head>");
  out.println("< body>你好!");
  out.println("< /body>< /html>");
  out.close();
}
}
式2:
  package test;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  public class test extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
  super.init(config);
}
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
  PrintWriter out = new PrintWriter (response.getOutputStream());
  out.println("< html>");
  out.println("< head>< title>Servlet1< /title>< /head>");
  out.println("< body>你好!");
  out.println("< /body>< /html>");
  out.close();
}
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
  PrintWriter out = new PrintWriter (response.getOutputStream());
  out.println("< html>");
  out.println("< head>< title>Servlet1< /title>< /head>");
  out.println("< body>你好!");
  out.println("< /body>< /html>");
  out.close();
}
}
  式1适合于作总控模块,此SERVLET作中间调度,根据不同的f值调用不同的SERVLET或方法。
式2适合于对html的get和post有不同要求的情况。
  但这并不是绝对的,式2就完全可以代替式1,只要在doGet()方法中写上doPost就与式1完全一样。
在init方法中执行的语句,只要这个servlet被启动了就一直有效,比如,我们在init()中new了一个对象,那么这个对象的内存空间就永远存在,除非显式地把这个对象赋为null,或重启服务。
  HttpServletRequest和HttpServletResponse两个对象实现http请求,它们有很多有用的方法,在下面的cookie和session治理中会细加描述。
  1, cookie治理 cookie用于在客户端保存个人所特有的信息,它采取在客户机写临时文件的机制。
  package test;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  public class test extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
  super.init(config);
}
  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //写cookie
  String CookieName ="js79"; //若是汉字则需编码
  String CookieValue = "yesky";//若是汉字则需编码
  Cookie cookie = new Cookie(CookieName,CookieValue);
  cookie.setMaxAge(age); // age = Integer.MAX_VALUE 永不过期
  cookie.setPath("/");
  //读cookie
  String value = null;
  Cookie[] cookies = request.getCookies();
  if (cookies != null) {
  for (int i=0; i< cookies.length; i++) {
  if (cookies[i].getName().equals(CookieName))
  value = cookies[i].getValue();
  break;
}
}
}
  response.setContentType("text/html");
  OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
  PrintWriter out = new PrintWriter (response.getOutputStream());
  out.println("< html>");
  out.println("< head>< title>test< /title>< /head>");
  out.println("cookie键:"+CookieName+"< br>");
  out.println("cookie值: "+value);
  out.println("< /body>< /html>");
  out.close();
}
}
  2,session治理
  Session在Servlet中是很有用的,它比cookie安全可靠灵活,但是治理起来有点麻烦,用得不好会造成服务器的开销很大,浪费资源。下面是一个基于Session治理一个对象的简单例子。
一个简单的bean对象TestObject
  package test;
  public class TestObject extends Object {
  int id = 0; public String cur="";
}
  package test;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  public class TestMan extends HttpServlet {
  public void init(ServletConfig config) throws ServletException {
  super.init(config);
}
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  int f = 1;
  if(request.getParameter("f")!=null)
  f =
  Integer.parseInt(request.getParameter("f"));
  switch(f){
  case 1: this.getResult(request,response);
  break;
  case 2:
  this.setSession(request,response);
  break;
}
}
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request,response);
}
  public void getResult(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {
  TestObject testObject = null;
  testObject = getStatus(request,response);
  String html = testObject.id; doWrite( response,html);
}
  public void setSession(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
  HttpSession session = request.getSession();
  TestObject testObject = null;
  testObject = getStatus(request,response);
  String tmp = null;
  tmp = request.getParameter("id");
  if(tmp != null) testObject.id = tmp;
  session.putValue("testObject ",article);
  getResult(request,response);
}
  private TestObject getStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  HttpSession session = request.getSession();
  TestObject testObject = null;
  if(session!=null){
  if(session.getValue("testObject ")!=null){
  testObject = (TestObject)session.getValue("testObject ");
}
  else{
  testObject = new TestObject ();
}
}
  else{
  testObject = new TestObject ();
}
  return testObject;
}
  private void doWrite(HttpServletResponse response,String html) throws   ServletException, IOException {
  PrintWriter out = response.getWriter();
  out.println(html);
  out.close();
}
  /////////////////////////////////////////////////////////
}
  若能轻松搞定上面的例子,相信读者对SERVLET已有了较为深刻的理解。
下面再介绍一个上传文件例子,其中汲及到了下载的免费JavaBean (如有感爱好的朋友,可来函索要免费JavaBean源代码,Email:js79@yesky.com)
  上传基本原理:由页面发出一个http请求,服务端得到请求后,解析多媒体协议,读出文件内容,写文件内容到服务器,所有的这些功能都封装到JavaBean中。
  上传文件的必需条件:Browser端< form>表单的ENCTYPE属性值必须为 multipart/form-data,它告诉我们传输的数据要用到多媒体传输协议,由于多媒体传输的都是大量的数据,所以规定上传文件必须是post方法,< input>的type属性必须是file。
  package upload;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import java.io.*;
  import java.util.*;
  public class UpLoadServlet extends HttpServlet {
  public void init(ServletConfig config) throws ServletException{
  super.init(config);
}
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
  +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
  +"< /HEAD>"
  +"< body>");
  out.println("< div align=´center´ valign=´top´>"
  +"< span class=´nava´>请你选择上传的文件(请注重文件大小只能在20K之内)< /span>< BR>"
  +"< form ENCTYPE=´multipart/form-data´ method=post action=´´>"
  +"< input type=´file´ name=´file´>"
  +"< input type=´submit´ value=´发送´>"
  +"< /form>"
  +"< /div>");
  out.println("< /body>< /html>");
  out.close();
}
  ////////
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  int tmpID = 1; try {
  MultipartRequest multi = new MultipartRequest(request,"/home/js79/html/", 5 * 1024 * 1024);
}
  catch(Exception e){
  tmpID = -1; System.out.println(e);
}
  if(tmpID == 1){
  out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
  +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
  +"< /HEAD>"
  +"< body>");
  out.println("上传成功!< /body>< /html>");
}
  else{
  out.println("< HTML>< HEAD>< TITLE>UpLoad< /TITLE>"
  +"< meta http-equiv=´Content-Type´ content=´text/html; charset=gb2312´>"
  +"< /HEAD>"
  +"< body>");
  out.println("上传不成功!< /body>< /html>");
}
  out.close();
}
}

Tags:实用 Servlet 应用

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接