Servlet從入門到精通三__二、Java

來源:互聯網
上載者:User

 

一、HttpServlet和一些開發細節

Servlet介面與兩個預設實作類別:GenericServlet、HttpServlet

1、HttpServlet指能夠處理HTTP請求的Servlet,它在原有Servlet介面上添加了一些與HTTP協議處理方法,它比Servlet介面的功能更為強大。因此開發人員在編寫Servlet時,通常應該繼承這個類,而避免直接去實現Servlet介面。

2、HttpServlet在實現Servlet介面時,覆寫了service()方法,改方法體內的代碼會自動判斷使用者的請求方式,如為GET請求,則調用HttpServlet的doGet方法,如為Post請求,則調用doPost方法。因此,開發人員在編寫Servlet時,通常只需要覆寫doGet或doPost方法,而不要去覆寫service方法。

 

查看servlet源碼,看HttpServlet源碼:

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) {                doGet(req, resp);            } else {                long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);                if (ifModifiedSince < (lastModified / 1000 * 1000)) {                    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 {         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);        }    }


 

3、執行個體

   1)建Web project

   2)建立一個servlet,如下

         

   

   3)點next,再點finish

   4)寫代碼:

 

package cn.itcast;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ServletDemo1 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.getOutputStream().write("Hello,HttpServlet!".getBytes());}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);  //這句話的意思:用戶端不管是Get方式還是Post方式,都由doGet來響應。}}


 

   5)、發布,開啟Tomcat,瀏覽器中輸入:

        http://localhost:8088/JavaWebChuan/servlet/ServletDemo1,

         可以看見   Hello,HttpServlet!

 

 

4、Myeclipse中改Servlet模板:

  進到MyEclipse安裝目錄  D:\MyEclipse 7.0M1,搜尋servlet.java

  找到Servlet.java這個檔案,把內容改為:

#---------------------------------------------#

# <aw:description>Template for Servlet</aw:description>

# <aw:version>1.1</aw:version>

# <aw:date>04/05/2003</aw:date>

# <aw:author>Ferret Renaud</aw:author>

#---------------------------------------------#

<aw:import>java.io.IOException</aw:import>

<aw:import>java.io.PrintWriter</aw:import>

<aw:import>javax.servlet.ServletException</aw:import>

<aw:import>javax.servlet.http.HttpServlet</aw:import>

<aw:import>javax.servlet.http.HttpServletRequest</aw:import>

<aw:import>javax.servlet.http.HttpServletResponse</aw:import>

<aw:parentClass>javax.servlet.http.HttpServlet</aw:parentClass>

<aw:constructor name="c1">

/**

 * Constructor of the object.

 */

public <aw:className/>() {

super();

}

</aw:constructor> 

 

<aw:method name="doGet">

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

}

</aw:method>

<aw:method name="doPost">

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request,response);

}

</aw:method>

<aw:method name="doPut">

/**

 * The doPut method of the servlet. <br>

 *

 * This method is called when a HTTP put request is received.

 * 

 * @param request the request send by the client to the server

 * @param response the response send by the server to the client

 * @throws ServletException if an error occurred

 * @throws IOException if an error occurred

 */

public void doPut(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Put your code here

}

</aw:method>

<aw:method name="doDelete">

/**

 * The doDelete method of the servlet. <br>

 *

 * This method is called when a HTTP delete request is received.

 * 

 * @param request the request send by the client to the server

 * @param response the response send by the server to the client

 * @throws ServletException if an error occurred

 * @throws IOException if an error occurred

 */

public void doDelete(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Put your code here

}

</aw:method>

<aw:method name="init">

/**

 * Initialization of the servlet. <br>

 *

 * @throws ServletException if an error occurs

 */

public void init() throws ServletException {

// Put your code here

}

</aw:method>

<aw:method name="destroy">

/**

 * Destruction of the servlet. <br>

 */

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

</aw:method>

<aw:method name="getServletInfo">

/**

 * Returns information about the servlet, such as 

 * author, version, and copyright. 

 *

 * @return String information about this servlet

 */

public String getServletInfo() {

return "This is my default servlet created by Eclipse";

}

</aw:method>

儲存,即可

 

聯繫我們

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