據說你叫Java(一)--Servlet簡介

本文是菜鳥教程閱讀筆記,詳細請前往菜鳥教程html

是什麼

Java Servlet是運行在Web服務器上的程序,它是做爲來自Web瀏覽器和服務器上的數據庫之間的中間層。java

簡單點說,咱們平時放在Tomcat上運行的的Java後端代碼就能夠稱爲Servlets Programweb

一張圖能夠看出Servlet在web程序中的位置。數據庫

clipboard.png

因此,Servlet就是接收瀏覽器或其餘HTTP客戶端發來的請求,根據請求操做數據庫,並返回請求所須要的數據。apache

怎麼用

設置CLASSPATH

因爲Servlet不是Java平臺標準版的組成部分,因此須要爲編譯器指定Servlet類的路徑。windows

windows下的C:\autoexec.bat中添加如下代碼後端

set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

Unix中的.cshrc文件中添加api

setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

正常咱們配置Tomcat的時候就已經配置好了,不須要單獨進行配置瀏覽器

生命週期

Servlet生命週期能夠當作從建立到終止的全過程。tomcat

  1. 經過調用init()方法進行初始化

  2. 調用service()方法來處理客戶端的請求

  3. 經過調用destory()方法終止。

  4. 最後經過JVM的垃圾回收器進行垃圾回收

經常使用的方法

init()方法

init()方法是用來建立Servlet的,一般能夠指定Servlet在服務器啓動的時候進行建立。

public void init() throws ServletException {
    //初始化
}

Servlet一旦被建立,服務器每接收一個請求時,都會產生一個新的線程,並調用service()方法。

service()方法

service()方法是處理請求的主要方法,也就是說咱們的業務邏輯都是經過這個方法或者這個方法的變式來實現的。

public void service(ServletRequest request, 
                    ServletResponse response) 
      throws ServletException, IOException{
}

doGet()doPost()方法是每次服務請求中最經常使用的方法,分別用於處理GET和POST請求。

destroy()方法

destroy()方法可讓Servlet 關閉數據庫鏈接、中止後臺線程、把 Cookie 列表或點擊計數器寫入到磁盤,並執行其餘相似的清理活動。


實現一個簡單的Servlet

在Eclipse中新建一個Dynamic Web Project項目。

clipboard.png

接着,在src目錄下新增一個package,命名爲com.servletLearn。再在這個包下面新增一個HelloWorld.java
Alt text

添加如下代碼到HelloWorld.java

package com.servletLearn;
/*
 * @description 第一個servlet實例
 * @author dahan
 */
// 導入必需的 java 庫
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// 擴展 HttpServlet 類
public class HelloWorld extends HttpServlet {

  private String message;
  public void init() throws ServletException
  {
      // 執行必需的初始化
      message = "Hello World";
  }
  public void doGet(HttpServletRequest request,HttpServletResponse response)
          throws ServletException, IOException
  {
      // 設置響應內容類型
      response.setContentType("text/html");
      // 實際的邏輯是在這裏
      PrintWriter out = response.getWriter();
      out.println("<h1>" + message + "</h1>");
  }
  public void destroy()
  {
      // 什麼也不作
  }
}

配置web.xml

<web-app>
  <servlet>
      <servlet-name>HelloWorld</servlet-name>
      <servlet-class>com.servletLearn.HelloWorld</servlet-class>
  </servlet>

  <servlet-mapping>
      <servlet-name>HelloWorld</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

啓動Tomcat,打開http://localhost:8080/servlet-learn/HelloWorld

clipboard.png

大功告成!

圖片描述

相關文章
相關標籤/搜索