新建web項目 – new Web Project – 選擇:javaee 5.0 建包 – com.gzsxt.wang 新建class:FirstServlet – 繼承:HttpServlet(javax.servlet.http.HttpServlet) 重寫service方法(兩個serv ...
新建web項目 – new Web Project – 選擇:javaee 5.0 建包 – com.gzsxt.wang 新建class:FirstServlet – 繼承:HttpServlet(javax.servlet.http.HttpServlet) 重寫service方法(兩個service方法中選擇帶 HttpServletRequest、HttpServletResponse參數 的) • 在web.xml中配置寫好的servlet – 配置Servlet作用有兩個: 1. 讓伺服器知道這個Servlet類的存在。 2. 讓URL和Servlet匹配,從而請求伺服器上的servlet
<servlet> <servlet-name>first</servlet-name> <servlet-class>com.gzsxt.wang.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>/111</url-pattern> </servlet-mapping>
安裝和啟動tomcat伺服器 • 將TOMCAT壓縮包解壓。 • 設置環境變數:
- – JAVA_HOME設置
- – 在tomcat子目錄:webapps中新建一個文件夾:abc
- – 將web項目的WebRoot目錄中所有的內容copy到abc中.
- – 重啟tomcat
- – http://localhost:8080/abc/one
- – http://127.0.0.1:8080/abc/one
- – http://自己機器的ip:8080/abc/one


/* * servlet 生命周期 1.載入並初始化 init()方法,只執行一次 2.運行 每當用戶發出一次請求時,調用service()方法。 * 1)當用戶請求時 * ,伺服器會創建一個線程,來調用servlet的service-->父類service-->父類的doGet/doPost方法:報405錯 * 解決辦法:重寫doPost方法或doGet方法 * 2)servlet是單例(設計模式之單例模式)的,節約記憶體。不需要每次請求創建對象去處理。 * * 3.銷毀 destroy()方法,只執行一次 */ int number = 0; @Override public void init() throws ServletException { System.out.println("servlet初始化!"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("子類的doGet方法"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("子類的doPost方法"); } /* * @Override protected void service(HttpServletRequest req, * HttpServletResponse resp) throws ServletException, IOException { * System.out.println("servlet運行了!!!!"); number++; * System.out.println(number); * * //super.service(req, resp); //調用父類的service方法 } */ @Override public void destroy() { System.out.println("servlet銷毀"); }子類一旦重寫父類的方法之後只會調用子類的方法 ,而不會調用父類的方法 預設的歡迎文件列表 apache-tom-->conf-->web.xml打開底部設置
<welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
在啟動時載入
<load-on-startup>1</load-on-startup>數字小的先被載入 為負數或者其他字元將不被載入,直到被調用時--懶漢式 http://127.0.0.1:8080/first_web/aaa 去除aaa
<welcome-file-list> <welcome-file>aaa</welcome-file> </welcome-file-list>去除first_web apache-tomcat -->webapps-->修改first_web文件名為ROOT 去除8080 apache-tom-->conf-->server.xml
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />修改port為80