hello2詳解

1.GreetingServlet.java(顯示問候頁面表單)html

此servlet重寫該doGet方法,實現GETHTTP方法。servlet顯示一個簡單的HTML問候表單,其提交按鈕就像hello1指定其操做的響應頁面同樣。如下摘錄以@WebServlet註釋開頭,註釋指定相對於上下文根的URL模式:java

 

package javaeetutorial.hello2;

import java.io.IOException;      //IOException表示發生某種I/O異常的信號。此類是由失敗或中斷的I/O操做產生的通常異常類。
import java.io.PrintWriter;      //io經常使用類,包裝流PrintWriter除了能夠包裝字節流OutputStream以外,還能包裝字符流Writer。
import javax.servlet.RequestDispatcher;    //定義一個對象,該對象接收來自客戶端的請求,並將它們發送到服務器上的任何資源(例如servlet,HTML文件或JSP文件)。
import javax.servlet.ServletException;    //定義servlet在遇到困難時能夠拋出的通常異常。
import javax.servlet.annotation.WebServlet;    //web服務中的,在Glassfish下lib中的包。
import javax.servlet.http.HttpServlet;     //提供要進行子類化的抽象類,以建立適用於Web站點的HTTP Servlet。
import javax.servlet.http.HttpServletRequest;    //擴展接口以提供HTTP Servlet的請求信息。
import javax.servlet.http.HttpServletResponse;    //擴展接口以在發送響應時提供特定於HTTP的功能。

/**
 * This is a simple example of an HTTP Servlet. It responds to the GET method of
 * the HTTP protocol.
 */
@WebServlet("/greeting")    //設置標註@webserverlet,容器會自動讀取裏面的信息。此標註告訴容器,若是請求的UEL是「/greeting」,則由GreetingServelet的實例提供服務。
public class GreetingServlet extends HttpServlet {    //建立一個公有類GreetingServlet繼承父類HttpServlet

    @Override          //覆蓋標註,意思是下面覆蓋HttpServlet中的doGet方法
    public void doGet(HttpServletRequest request,    //參數:—包含客戶端對servlet的請求的對象
            HttpServletResponse response)     //參數:包含servlet發送給客戶端的響應的對象
            throws ServletException, IOException {    //拋出: - 若是在servlet處理GET請求時檢測到輸入或輸出錯誤; - 若是沒法處理GET請求

        response.setContentType("text/html");    //發送給客戶端的文章類型
        response.setBufferSize(8192);    //發送給客戶端的響應對象的緩衝大小是8192
        try (PrintWriter out = response.getWriter()) {    //獲取PrintWriter流,用來在客戶端輸出
            out.println("<html lang=\"en\">"      //如下是html標記語言用來顯示頁面
                    + "<head><title>Servlet Hello</title></head>");
            
            // then write the data of the response
            out.println("<body  bgcolor=\"#ffffff\">"
                    + "<img src=\"resources/images/duke.waving.gif\" "
                    + "alt=\"Duke waving his hand\">"
                    + "<form method=\"get\">"
                    + "<h2>Hello, my name is Duke. What's yours?</h2>"
                    + "<input title=\"My name is: \" type=\"text\" "
                    + "name=\"username\" size=\"25\"/>"
                    + "<p></p>"
                    + "<input type=\"submit\" value=\"Submit\"/>"
                    + "<input type=\"reset\" value=\"Reset\"/>"
                    + "</form>");
            
            String username = request.getParameter("username");    //定義一個字符串username並對它賦從request中拿出名字叫userName的值
            if (username != null && username.length() > 0) {    //若是username不爲空而且長度大於0
                RequestDispatcher dispatcher =
                        getServletContext().getRequestDispatcher("/response");    //獲取jsp上下文裏邊存儲了各變量的信息(值),把一個命令發送到瀏覽器,讓瀏覽器對指定的URL提出請求(此處的URL只能使用絕對路徑)
                
                if (dispatcher != null) {
                    dispatcher.include(request, response);      //若是接收到的客戶端的請求不爲空時,記錄保留request和response,之後不能再修改response裏表示狀態的信息
                }
            }
            out.println("</body></html>");
        }
    }

    @Override    //覆蓋
    public String getServletInfo() {    //getServletInfo()方法是一個可選的方法,它提供有關servlet的信息,如做者、版本、版權
        return "The Hello servlet says hello.";    //返回說明這個servelet的信息是says hello
    }
}
ServletRequestServletResponsereqHttpServletRequestrespHttpServletResponsejava.io.IOExceptionServletException

 

詳細使用方法(來源於API文檔):
protected void
doGetHttpServletRequest  req, HttpServletResponse  resp) 拋出ServletException java.io.IOException
由服務器調用(經過 service 方法)以容許servlet處理GET請求。

重寫此方法以支持GET請求也會自動支持HTTP HEAD請求。HEAD請求是一個GET請求,它在響應中不返回任何主體,只返回請求頭字段。web

覆蓋此方法時,請讀取請求數據,編寫響應頭,獲取響應的編寫器或輸出流對象,最後編寫響應數據。最好包含內容類型和編碼。使用PrintWriter對象返回響應時,請在訪問PrintWriter對象以前設置內容類型 apache

servlet容器必須在提交響應以前寫入標頭,由於在HTTP中,標頭必須在響應主體以前發送。api

在可能的狀況下,設置Content-Length標頭(使用 ServletResponse.setContentLength(int)方法),以容許servlet容器使用持久鏈接將其響應返回給客戶端,從而提升性能。若是整個響應適合響應緩衝區,則自動設置內容長度。瀏覽器

使用HTTP 1.1分塊編碼(這意味着響應具備Transfer-Encoding標頭)時,請不要設置Content-Length標頭。tomcat

GET方法應該是安全的,即沒有任何反作用,用戶對此負責。例如,大多數表單查詢沒有反作用。若是客戶端請求旨在更改存儲的數據,則該請求應使用其餘一些HTTP方法。安全

GET方法也應該是冪等的,這意味着它能夠安全地重複。有時使方法安全也使其成爲冪等的。例如,重複查詢既安全又冪等,但在線購買產品或修改數據既不安全也不是冪等。服務器

若是請求格式不正確,則doGet 返回HTTP「錯誤請求」消息。jsp

 

參數:
req HttpServletRequest 包含客戶端對servlet的請求的對象
resp HttpServletResponse 包含servlet發送給客戶端的響應的對象
拋出:
java.io.IOException  - 若是在servlet處理GET請求時檢測到輸入或輸出錯誤
ServletException  - 若是沒法處理GET請求

 

2.ResponseServlet.java(響應頁面)

此servlet也覆蓋該doGet方法,僅顯示響應。如下摘錄以@WebServlet 註釋開頭,註釋指定相對於上下文根的URL模式:

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

/**
 * This is a simple example of an HTTP Servlet.  It responds to the GET
 * method of the HTTP protocol.
 */
@WebServlet("/response")
public class ResponseServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        try (PrintWriter out = response.getWriter()) {
            String username = request.getParameter("username");    //同上
            if (username != null && username.length() > 0) {    //若是username不爲空且長度大於0
                out.println("<h2>Hello, " + username + "!</h2>");    //打印Hello username
            }
        }
    }

    @Override
    public String getServletInfo() {
        return "The Response servlet says hello.";

    }
}
相關文章
相關標籤/搜索