Java Servlet 編程及應用之二

來源:互聯網
上載者:User

  編寫Servlet所需要的開發環境

  進行Servlet開發所需要的基本環境是JSDK以及一個支援Servlet的Web伺服器。

  1.JSDK(Java Servlet Development Kit)

  JSDK包含了編譯Servlet應用程式所需要的Java類庫以及相關的文檔。對於利用Java 1.1進行開發的使用者,必須安裝JSDK。JSDK已經被整合進Java 1.2 Beta版中,如果利用Java 1.2或以上版本進行開發,則不必安裝JSDK。

  JSDK可以在Javasoft公司的網站免費下載,其地址是:   http://www.sun.com/software/jwebserver/redirect.html

  2.支援Servlet的Web伺服器

  Servlet需要運行在支援Servlet的Web伺服器上。目前支援Servlet的Web伺服器SUN公司的JSWDK1.0.1。如果現有的Web伺服器不支援Servlet,則可以利用一些第三方廠商的伺服器增加件(add-ons)來使Web伺服器支援Servlet,這其中Live Software公司(http://www.livesoftware.com)提供了一種稱為JRun的產品,通過安裝JRun的相應版本,可以使Microsoft IIS和Netscape Web Server支援Servlet。

  開發Servlet的過程

  下面舉一個簡單的Servlet 例子來說明開發Servlet的過程。

  1.編寫Servlet代碼

  Java Servlet API是一個標準的Java擴充程式包,包含兩個Package∶javax.servlet和javax.servlet.http。對於想開發基於客戶自訂協議的開發人員,應該使用javax.servlet包中的類與介面;對於僅利用HTTP協議與用戶端進行互動的開發人員,則只需要使用javax.servlet.http包中的類與介面進行開發即可。

  下面是一個servlet的程式碼(RequestInfoExample.java)∶

import java.io.*;
import java.servlet.*;
import javax.servlet.*;
public class RequestInfoExample extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws IOException, ServletException
 {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<body>");
  out.println("<head>");
  out.println("<title>Request Information Example</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h3>Request Information Example</h3>");
  out.println("Method: " + request.getMethod());
  out.println("Request URI: " + request.getRequestURI());
  out.println("Protocol: " + request.getProtocol());
  out.println("PathInfo: " + request.getPathInfo());
  out.println("Remote Address: " + request.getRemoteAddr());
  out.println("</body>");
  out.println("</html>");
 }
 public void doPost(HttpServletRequest request, HttpServletResponse res)
 throws IOException, ServletException
 {
  doGet(request, response);
 }
}

  該servlet實現如下功能∶當使用者通過瀏覽器訪問該servlet時,該servlet向用戶端瀏覽器返回一個HTML頁面∶



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.