servlet源碼解讀(一)

來源:互聯網
上載者:User

   上班時間實在沒事,但是自己不能去閑著。

    閑來無事就翻開servlet的源碼來看看,來領略下大神的境界。

    順便沾點仙氣。

   1. HttpServlet

    我想凡是做過servlet開發的都應該知道個類。很多時候做web開發都是直接繼承這個HttpServlet類。然後實現doGet,doPost方法。

    來看看它的源碼:

    首先是定義了一對靜態變數:

    private static final String METHOD_DELETE = "DELETE";    private static final String METHOD_HEAD = "HEAD";    private static final String METHOD_GET = "GET";    private static final String METHOD_OPTIONS = "OPTIONS";    private static final String METHOD_POST = "POST";    private static final String METHOD_PUT = "PUT";    private static final String METHOD_TRACE = "TRACE";    private static final String HEADER_IFMODSINCE = "If-Modified-Since";    private static final String HEADER_LASTMOD = "Last-Modified";        private static final String LSTRING_FILE ="javax.servlet.http.LocalStrings";    private static ResourceBundle lStrings =ResourceBundle.getBundle(LSTRING_FILE);

  包括各種方法名的定義,再加了Http請求的參數.

  再在看看doGet方法是怎麼實現的:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException    {String protocol = req.getProtocol();String msg = lStrings.getString("http.method_get_not_supported");if (protocol.endsWith("1.1")) {    resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);} else {    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);}    }

 

   一般而言,使用者都會選擇覆蓋doGet和doPost方法,或者是直接選擇service方法。

   這裡需要注意一點就是:

    String protocol = req.getProtocol();

   用來擷取瀏覽器在協議,判斷是不是用的http1.1協議。其他的方法類似,就不看了。

   那麼再看看service:

protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException    {String method = req.getMethod();if (method.equals(METHOD_GET)) {    long lastModified = getLastModified(req);    if (lastModified == -1) {// servlet doesn't support if-modified-since, no reason// to go through further expensive logicdoGet(req, resp);    } else {long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);if (ifModifiedSince < (lastModified / 1000 * 1000)) {    // If the servlet mod time is later, call doGet()                    // Round down to the nearest second for a proper compare                    // A ifModifiedSince of -1 will always be less    maybeSetLastModified(resp, lastModified);    doGet(req, resp);} else {    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);}    }} else if (method.equals(METHOD_HEAD)) {    long lastModified = getLastModified(req);    maybeSetLastModified(resp, lastModified);    doHead(req, resp);} else if (method.equals(METHOD_POST)) {    doPost(req, resp);    } else if (method.equals(METHOD_PUT)) {    doPut(req, resp);    } else if (method.equals(METHOD_DELETE)) {    doDelete(req, resp);    } else if (method.equals(METHOD_OPTIONS)) {    doOptions(req,resp);    } else if (method.equals(METHOD_TRACE)) {    doTrace(req,resp);    } else {    //    // Note that this means NO servlet supports whatever    // method was requested, anywhere on this server.    //    String errMsg = lStrings.getString("http.method_not_implemented");    Object[] errArgs = new Object[1];    errArgs[0] = method;    errMsg = MessageFormat.format(errMsg, errArgs);        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);}    }

 

  其實在HttpServlet中是根據擷取的mehtod參數,在service中調用相應在方法。這裡就涉及到了一個問題。

  在很多時候我們可以都是選擇覆蓋doget和dopost方法。其實如果在你知道get和post請求都是調用一個方法的時候 。

  最簡單在處理方式是直接選擇覆蓋service方法。而如果需要對兩種不同和請求做不同的判斷,剛可以選擇分別覆蓋。

 

2 ServletConfig

   可能很多人都聽說過,不就是在初始化的時候對web.xml的的一些配置嗎?

   但是我看到的是,這竟然只是一個介面,沒有任何的實現。(至少我曾經一直以為他會是一個類,那麼為什麼呢?)

    說是我去找了很久,想要起到他們實作類別哪裡?

    下面看下ServletConfig的介面:

public interface ServletConfig {        public String getServletName();    public ServletContext getServletContext();            public String getInitParameter(String name);    public Enumeration getInitParameterNames();}

   去掉注釋之後,發現很簡單有木有。我在想一個介面能做什麼呢?他一定有他有實作類別。

   那麼來看看,很幸運在GenericServlet看到對它的實現 :

   但是很不幸的是:

   都是看到了這樣一句代碼:

   

ServletConfig sc = getServletConfig();

  那麼getServltConfig()方法是什麼呢:

    public ServletConfig getServletConfig() {return config;    }

   竟然只是返回一個變數:那麼變數又是怎麼定義的?

   真真在大頭來了,看看上面在變數定義:

  private static final String LSTRING_FILE = "javax.servlet.LocalStrings";   private static ResourceBundle lStrings =        ResourceBundle.getBundle(LSTRING_FILE);   private transient ServletConfig config;

 什嗎?竟然是transient?從來沒見過。百度N次。終於看明白了些。

 就是說不可序列化的意思。我不知道我這樣說是否正確。但是我覺得沒什麼問題。

 看下面個列子(百度過來的,覺得還不錯!):

public class People implements Serializable {private static final long serialVersionUID = 8294180014912103005L;/** * 使用者名稱 */private String username;/** * 密碼 */private transient String password;}

 

public static void main(String[] args) throws Exception {People p = new People();p.setUsername("snowolf");p.setPassword("123456");System.err.println("------操作前------");System.err.println("username: " + p.getUsername());System.err.println("password: " + p.getPassword());ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("people.txt"));oos.writeObject(p);oos.flush();oos.close();ObjectInputStream ois = new ObjectInputStream(new FileInputStream("people.txt"));p = (People) ois.readObject();ois.close();System.err.println("------操作後------");System.err.println("username: " + p.getUsername());System.err.println("password: " + p.getPassword());}

輸出如下:

------操作前------

 username: snowolf

password: 123456

 ------操作後------

username: snowolf

password: null

我想你應該明白一些了。在做序列化的時候,需要將資料寫入到硬碟,那麼如果用transient修飾。剛不會儲存。該變數的值只會儲存在調用者的記憶體中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.