天天看點

Servlet技術簡介

servlet是單例多線程!

servlet是單例多線程!!

servlet是單例多線程!!!

1 Servlet簡介

servlet是一種伺服器端的應用程式,具有獨立于平台和協定的特性,可以生成動态的web頁面。它擔當客戶請求(web浏覽器或其他HTTP客戶程式)和伺服器響應(HTTP伺服器上的資料庫或應用程式)的中間層。

    JSP是servlet的一種形式,每個JSP頁面實際上就是一個servlet執行個體——JSP頁面由servlet引擎轉換成servlet,servlet負責響應客戶請求。也就是說使用JSP實際上還是使用servlet,因為web應用中每個JSP頁面都會由servlet容器生成servlet。

Servlet技術簡介

圖1 servlet應用程式的體系結構

2 建立第一個servlet

import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello")
public class Servlet extends javax.servlet.http.HttpServlet {

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("hello:post");
        PrintWriter out = response.getWriter();
        out.print("<h1 style='color:red'>post</h1>");
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("hello:get");
        PrintWriter out = response.getWriter();
        out.print("<h1 style='color:red'>get</h1>");
    }
}      
Servlet技術簡介

3 servlet的生命周期

servlet的生命周期由servlet容器控制,該容器建立servlet的執行個體。servlet的生命周期就是指servlet執行個體在建立之後響應用戶端請求直至銷毀的全過程。servlet執行個體的首次建立取決于servlet的首次調用。servlet接口定義了servlet生命周期的三個方法,這些方法就是init(),service(),destroy().

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello")
public class ServletDemo extends javax.servlet.http.HttpServlet {

    public ServletDemo(){
        super();
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("hello:post");
        PrintWriter out = response.getWriter();
        out.print("<h1 style='color:red'>post</h1>");
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("hello:get");
        PrintWriter out = response.getWriter();
        out.print("<h1 style='color:red'>get</h1>");
    }

    public void destroy(){
        System.out.println("destroy");
    }
    public void init(){
        System.out.println("init");
    }

}