Servlet簡介

一,什麼是Servlet?  

Servlet 是用 Java 編寫的服務器端程序模塊,用以擴展 WebServer 的功能。  Servlet 被加載到 Web 服務器上, 並在其中運行。Servlet 使用 HTTP 服務器接收和響應客戶機發出的請求。

二,Servlet 能夠執行哪些功能?

 1,能夠創建並返回整個 HTML Web 頁面,根據客戶請求的性質而具有動態內容。  

2,能夠創建 HTML Web 頁面的動態部分,並嵌入到現有靜態 HTML 頁面中。  

3,可以與服務器上的其他資源進行通信,包括數據庫、其他 Java 應用程序、以及用其他語言編寫的應用程序。

 4,能夠處理與多個 Web 客戶機的連接,接收來自多個 Web 客戶機的輸入信息,並將結果廣播到多個 Web 客戶機。  

5,能夠打開對 Web 客戶機上 applet 的個別連接,並保持連接處於打開狀態,允許在這個單一連接上進行多種數據傳遞。    這種效能使客戶機和服務器能夠容易地進行會話。    

三,什麼是Servlet組件  

Servlet組件(即Servlet容器)實際是一個程序模塊(Class文件),那麼服務器在接收到客戶發送的URL請求,   就根據URL請求中的資源部分在服務器找到相應的Servlet組件資源然後裝載到服務器並執行;   這個過程是所有J2EE服務器都共有的標準過程。   

四,Servlet的生命週期。  

Servlet的生命週期由Servlet容器控制,由容器創建Servlet實例;

 整個生命週期:   

1,實例化:加載Servlet組件類,由容器創建Servlet實例;      

  2,初始化:執行init方法,初始化Servlet實例;     

ServletConfig接口實現對象:向Servlet傳遞配置信息,包含Servlet初始化信息。以名-值對形式提供。     Servlet使用ServletConfig接口與Servlet容器通信。     通過getServletConfig方法獲得當前ServletConfig接口實現對象。        

3,服務:調用Servlet組件GenericServlet類的Service方法處理客戶請求;   

  ServletRequest接口和ServletResponse接口的實現對象來 處理請求 和 發送響應。    

 如果URL爲GET請求 則執行HttpServlet類的doGet方法;如果URL爲POST請求則執行HttpServlet類的doPost方法;   

4,釋放:執行Destory方法釋放Servlet實例資源;    

 五,Servlet體系結構和層次結構  

1,Servlet體系結構        

   

            ------請求   --->                            ------->                              ------->                       

客戶端                              HTTP服務器                    Servlet容器                        Servlet    

             <----- 響應  ----                            <---------                          <-------          

                

2,Servlet層次結構    

Servlet是實現javax.servlet.Servlet接口的對象,大多數Servlet通過GenericServlet或HttpServlet進行擴展.   Servlet API 由兩個程序包組成   

 javax.servlet  包   

類:      

ServletInputStream類:從客戶端讀取二進制數據;      

ServletOutputStream類;向客戶端發送二進制數據;      

GenericServlet類:抽象類,定義了一個通用的,獨立於底層協議的Servlet。

   接口:     

 Servlet接口:管理Sevlet。定義實現Servlet的必須方法。一個Servlet必須實現Servlet接口或Servlet接口的擴展。      

ServletConfig接口:Servlet初始化時,向Servlet傳遞配置信息。      

ServletContext接口;Servlet上下文,使Servlet與其他的Servlet容器進行交互通信。     

 ServletRequest接口:向Servlet客戶端提供請求信息      

ServletResponse接口;Servlet向客戶端提供響應信息。         

javax.servlet.http     包 

類:      

 Cookie類       

HttpServlet類:抽象類,繼承自GenericServlet。應用於HTTP協議的請求和響應的Servlet。     

 接口:      

 HttpSession接口:      

 HttpAttributeListener接口:會話的屬性監聽接口;      

 HttpServletRequest接口;擴展ServletRequest接口,向Servlet客戶端提供HTTP請求信息。     

 HttpServletResponse接口;擴展ServletResponse接口,Servlet向客戶端提供HTTP響應信息。   

  總體可以分爲:   

 Servlet類:     實現具體協議的業務類,其目的是一個業務實現的WEB組件類;    

Servlet接口:     該接口獨立於協議實現,其目的是爲了定義服務器的組件標準;    

GenericServlet抽象類:     該類提供了一個獨立於協議的實現,其目的是爲了滿足服務器;    

HttpServlet:     該類實現了HTTP協議,其目的是爲了讓客戶程序擴展;

示例:登錄處理,將表單提交給Servlet處理

LoginServlet.java

package com.qu.servlet;



import java.io.IOException;

import java.io.PrintWriter;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



public class LoginServlet extends HttpServlet {



	/**

	 * 

	 */

	private static final long serialVersionUID = 1L;

	

	public LoginServlet() {

		super();

	}



	@Override

	public void doGet(HttpServletRequest request, HttpServletResponse response)

			throws ServletException, IOException {

		

		response.setContentType("text/html;charset=gb2312"); 

		request.setCharacterEncoding("gb2312"); 

		

		String userName = request.getParameter("user");

		String userPswd = request.getParameter("pswd");

		

		PrintWriter out = response.getWriter();

		

		out.println("<html>");

		out.println("<head><title>Login</title></head>");

		out.println("<body>");

		

		if (this.checkLogin(userName, userPswd)){

			out.println("用戶名爲:" + userName);

			out.println(" 歡迎您訪問本網站!");

		}else{

			out.println("您的用戶名或密碼有誤,請重新登錄!");

		}

		

		out.println("</body>");

		out.println("</html>");

		out.close();

	}



	@Override

	public void doPost(HttpServletRequest req, HttpServletResponse resp)

			throws ServletException, IOException {

		this.doGet(req, resp);

	}

	

	public boolean checkLogin(String userName, String userPswd)

	{

		if (userName.equals("") || userName.length() > 12 || userName.length() < 4){

			

			return false;

		}

		else if(userPswd.equals("") || userPswd.length() > 12 || userPswd.length() < 6){

			return false;

		}else{

			return true;

		}

		

	}

}
 

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'index.jsp' starting page</title>

	<meta http-equiv="pragma" content="no-cache">

	<meta http-equiv="cache-control" content="no-cache">

	<meta http-equiv="expires" content="0">    

	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

	<meta http-equiv="description" content="This is my page">

	<!--

	<link rel="stylesheet" type="text/css" href="styles.css">

	-->

  </head>

  

  <body>

    <form action="login" method="post" > 

    	用戶名:<input type="text" name="user"/><BR/>

    	密 碼 :<input type="password" name="pswd"><BR/>

    	<input type="submit" value="提交"/> <input type="reset" value="重置"/>

    </form>

  </body>

</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" 

	xmlns="http://java.sun.com/xml/ns/j2ee" 

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 

	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <welcome-file-list>

    <welcome-file>login.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- Servlet -->

  <!-- login -->

  <servlet>

	<servlet-name>LoginServlet</servlet-name>

	<servlet-class>com.qu.servlet.LoginServlet</servlet-class>  

  </servlet>

  

  <!-- Servlet mapping -->

  <!-- login mapping-->

  <servlet-mapping>

  	<servlet-name>LoginServlet</servlet-name>

  	<url-pattern>/login</url-pattern>

  </servlet-mapping>

</web-app>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章