1.1 步驟:html
1)編寫java類,繼承HttpServlet類java
2)從新doGet和doPost方法web
3)Servlet程序交給tomcat服務器運行!!編程
3.1 servlet程序的class碼拷貝到WEB-INF/classes目錄瀏覽器
3.2 在web.xml文件中進行配置tomcat
<!-- 配置一個servlet --> <!-- servlet的配置 --> <servlet> <!-- servlet的內部名稱,自定義。儘可能有意義 --> <servlet-name>FirstServlet</servlet-name> <!-- servlet的類全名: 包名+簡單類名 --> <servlet-class>gz.itcast.a_servlet.FirstServlet</servlet-class> </servlet> <!-- servlet的映射配置 --> <servlet-mapping> <!-- servlet的內部名稱,必定要和上面的內部名稱保持一致!! --> <servlet-name>FirstServlet</servlet-name> <!-- servlet的映射路徑(訪問servlet的名稱) --> <url-pattern>/first</url-pattern> </servlet-mapping>
tomcat服務器啓動時,首先加載webapps中的每一個web應用的web.xml配置文件。安全
http://: http協議服務器
localhost: 到本地的hosts文件中查找是否存在該域名對應的IP地址多線程
127.0.0.1併發
8080: 找到tomcat服務器
/day10 在tomcat的webapps目錄下找 day10的目錄
/first 資源名稱。
1)在day10的web.xml中查找是否有匹配的url-pattern的內容(/first)
2)若是找到匹配的url-pattern,則使用當前servlet-name的名稱到web.xml文件中查詢是否相同名稱的servlet配置
3)若是找到,則取出對應的servlet配置信息中的servlet-class內容:
字符串: gz.itcast.a_servlet.FirstServlet
經過反射:
a)構造FirstServlet的對象
b)而後調用FirstServlet裏面的方法
<servlet-mapping> <!-- servlet的內部名稱,必定要和上面的內部名稱保持一致!! --> <servlet-name>FirstServlet</servlet-name> <!-- servlet的映射路徑(訪問servlet的名稱) --> <url-pattern>/first</url-pattern> </servlet-mapping>
url-pattern 瀏覽器輸入
精確匹配 /first http://localhost:8080/day10/first
/itcast/demo1 http://localhost:8080/day10/itcast/demo1
模糊匹配 /* http://localhost:8080/day10/任意路徑
/itcast/* http://localhost:8080/day10/itcast/任意路徑
*.後綴名 http://localhost:8080/day10/任意路徑.do
*.do
*.action
*.html(僞靜態)
注意:
1)url-pattern要麼以 / 開頭,要麼以*開頭。 例如, itcast是非法路徑。
2)不能同時使用兩種模糊匹配,例如 /itcast/*.do是非法路徑
3)當有輸入的URL有多個servlet同時被匹配的狀況下:
3.1 精確匹配優先。(長的最像優先被匹配)
3.2 之後綴名結尾的模糊url-pattern優先級最低!!!
servlet的缺省路徑(<url-pattern>/</url-pattern>)是在tomcat服務器內置的一個路徑。該路徑對應的是一個DefaultServlet(缺省Servlet)。這個缺省的Servlet的做用是用於解析web應用的靜態資源文件。
問題: URL輸入http://localhost:8080/day10/index.html 如何讀取文件????
1)到當前day10應用下的web.xml文件查找是否有匹配的url-pattern。
2)若是沒有匹配的url-pattern,則交給tomcat的內置的DefaultServlet處理
3)DefaultServlet程序到day10應用的根目錄下查找是存在一個名稱爲index.html的靜態文件。
4)若是找到該文件,則讀取該文件內容,返回給瀏覽器。
5)若是找不到該文件,則返回404錯誤頁面。
結論: 先找動態資源,再找靜態資源。
Servlet的生命週期: servlet類對象何時建立,何時調用什麼方法,何時銷燬。
之前的對象: new Student(); stu.study(); stu=null;
Servlet程序的生命週期由tomcat服務器控制的!!!!
構造方法: 建立servlet對象的時候調用。默認狀況下,第一次訪問servlet的時候建立servlet對象 只調用1次。證實servlet對象在tomcat是單實例的。
init方法: 建立完servlet對象的時候調用。只調用1次。
service方法: 每次發出請求時調用。調用n次。
destroy方法: 銷燬servlet對象的時候調用。中止服務器或者從新部署web應用時銷燬servlet對象。
只調用1次。
Tomtcat內部代碼運行:
1)經過映射找到到servlet-class的內容,字符串: gz.itcast.a_servlet.FirstServlet
2)經過反射構造FirstServlet對象
2.1 獲得字節碼對象
Class clazz = class.forName("gz.itcast.a_servlet.FirstServlet");
2.2 調用無參數的構造方法來構造對象
Object obj = clazz.newInstance(); ---1.servlet的構造方法被調用
3)建立ServletConfig對象,經過反射調用init方法
3.1 獲得方法對象
Method m = clazz.getDeclareMethod("init",ServletConfig.class);
3.2 調用方法
m.invoke(obj,config); --2.servlet的init方法被調用
4)建立request,response對象,經過反射調用service方法
4.1 獲得方法對象
Method m=clazz.getDeclareMethod("service",HttpServletRequest.class,HttpServletResponse.class);
4.2 調用方法
m.invoke(obj,request,response); --3.servlet的service方法被調用
5)當tomcat服務器中止或web應用從新部署,經過反射調用destroy方法
5.1 獲得方法對象
Method m = clazz.getDeclareMethod("destroy",null);
5.2 調用方法
m.invoke(obj,null); --4.servlet的destroy方法被調用
代碼演示:
package com.http.servletExercise; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class servlet extends HttpServlet { private ServletConfig path; /** * Constructor of the object. */ public servlet() { System.out.println("建立一個servlet!"); } @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub this.path = config; super.init(config); } private void destory() { // TODO Auto-generated method stub System.out.println("銷燬一個servlet"); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("收到一個請求!"); super.service(req, resp); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 */ int count = 0; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("gb2312"); synchronized (servlet.class) { response.getWriter().write("這是第" + count + "個請求!"); count++; // System.out.println(path.getInitParameter("path") + "MyWeb/temp.txt");/MyWeb/WebRoot/temp.txt BufferedReader in = new BufferedReader(new FileReader(path.getInitParameter("path") + "MyWeb/WebRoot/temp.txt")); String str; while((str = in.readLine()) != null){ System.out.println(str); } in.close(); } Enumeration<String> names = this.getServletConfig().getInitParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement(); System.out.println(name + ":" + this.getServletConfig().getInitParameter(name)); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
默認狀況下,第一次訪問servlet的時候建立servlet對象。若是servlet的構造方法或init方法中執行了比較多的邏輯代碼,那麼導用戶第一次訪問sevrlet的時候比較慢。
改變servlet建立對象的時機: 提早到加載web應用的時候!!!
在servlet的配置信息中,加上一個<load-on-startup>便可!!
<servlet> <servlet-name>LifeDemo</servlet-name> <servlet-class>gz.itcast.c_life.LifeDemo</servlet-class> <!-- 讓servlet對象自動加載 --> <load-on-startup>1</load-on-startup> 注意: 整數值越大,建立優先級越低!! </servlet>
注意: servlet對象在tomcat服務器是單實例多線程的。
由於servlet是多線程的,因此當多個servlet的線程同時訪問了servlet的共享數據,如成員變量,可能會引起線程安全問題。
解決辦法:
1)把使用到共享數據的代碼塊進行同步(使用synchronized關鍵字進行同步)
2)建議在servlet類中儘可能不要使用成員變量。若是確實要使用成員,必須同步。並且儘可能縮小同步代碼塊的範圍。(哪裏使用到了成員變量,就同步哪裏!!),以免由於同步而致使併發效率下降。
Servlet學習:
HttpServletRequest 請求對象:獲取請求信息
HttpServletResponse 響應對象: 設置響應對象
ServletConfig對象 servlet配置對象
ServletContext對象; servlet的上下文對象
ServletConfig對象: 主要是用於加載servlet的初始化參數。在一個web應用能夠存在多個ServletConfig對象(一個Servlet對應一個ServletConfig對象)
建立時機: 在建立完servlet對象以後,在調用init方法以前建立。
獲得對象: 直接從有參數的init方法中獲得!!!
<servlet> <servlet-name>ConfigDemo</servlet-name> <servlet-class>gz.itcast.f_config.ConfigDemo</servlet-class> <!-- 初始參數: 這些參數會在加載web應用的時候,封裝到ServletConfig對象中 --> <init-param> <param-name>path</param-name> <param-value>e:/b.txt</param-value> </init-param> </servlet>
注意: servlet的參數只能由當前的這個sevlet獲取!!!!
ServletConfig的API:
java.lang.String getInitParameter(java.lang.String name) 根據參數名獲取參數值
java.util.Enumeration getInitParameterNames() 獲取全部參數
ServletContext getServletContext() 獲得servlet上下文對象
java.lang.String getServletName() 獲得servlet的名稱
代碼練習:
package com.servlet.context; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class contextExercise extends HttpServlet { /** * Constructor of the object. */ public contextExercise() { super(); } /** * 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 } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); String contextPath = context.getContextPath(); System.out.println(contextPath); System.out.println(context.getInitParameter("AAA")); Enumeration<String> names = context.getInitParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement(); System.out.println(name + ":" + context.getInitParameter(name)); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
ServletContext對象 ,叫作Servlet的上下文對象。表示一個當前的web應用環境。一個web應用中只有一 個ServletContext對象。
建立時機:加載web應用時建立ServletContext對象。
獲得對象: 從ServletConfig對象的getServletContext方法獲得
咱們設計:
建立ServletConfig對象
public void init( ServletConfig config,ServletContext context ){ 多了一個參數
獲得ServletConfig對象
獲得ServletContext對象;
}
Sun公司設計
1)建立ServletContext對象 ServletContext context = new ServletContext()
2)建立ServletConfig對象 ServetConfig config = new ServletConfig();
config.setServletContxt(context);
class ServletConfig{
ServletContext context;
public ServletContext getServletContxt(){
return contxt;
}
}
public void init( ServletConfig config ){
獲得ServletConfig對象
從ServletConfig對象中獲得ServletContext對象
SerlvetContext context = config.getServletContext();
}
10.1 ServletContext對象的核心API(做用)
java.lang.String getContextPath() --獲得當前web應用的路徑
java.lang.String getInitParameter(java.lang.String name) --獲得web應用的初始化參數
java.util.Enumeration getInitParameterNames()
void setAttribute(java.lang.String name, java.lang.Object object) --域對象有關的方法
java.lang.Object getAttribute(java.lang.String name)
void removeAttribute(java.lang.String name)
RequestDispatcher getRequestDispatcher(java.lang.String path) --轉發(相似於重定向)
java.lang.String getRealPath(java.lang.String path) --獲得web應用的資源文件
java.io.InputStream getResourceAsStream(java.lang.String path)
java.lang.String getContextPath() 用在請求重定向的資源名稱中
java.lang.String getInitParameter(java.lang.String name) --獲得web應用的初始化參數
java.util.Enumeration getInitParameterNames()
web應用參數可讓當前web應用的全部servlet獲取!!!
域對象:做用是用於保存數據,獲取數據。能夠在不一樣的動態資源之間共享數據。
案例:
Servlet1 Servlet2
name=eric
response.sendRedirect("/Servlet2?name=eric") String request.getParameter("name");
保存到域對象中 從域對象獲取
Student
方案1: 能夠經過傳遞參數的形式,共享數據。侷限:只能傳遞字符串類型。
方案2: 可使用域對象共享數據,好處:能夠共享任何類型的數據!!!!!
ServletContext就是一個域對象!!!!
保存數據:void setAttribute(java.lang.String name, java.lang.Object object)
獲取數據: java.lang.Object getAttribute(java.lang.String name)
刪除數據: void removeAttribute(java.lang.String name)
ServletContext域對象:做用範圍在整個web應用中有效!!!
全部域對象:
HttpServletRequet 域對象
ServletContext域對象
HttpSession 域對象
PageContext域對象
RequestDispatcher getRequestDispatcher(java.lang.String path)
1)轉發
a)地址欄不會改變
b)轉發只能轉發到當前web應用內的資源
c)能夠在轉發過程當中,能夠把數據保存到request域對象中
2)重定向
a)地址欄會改變,變成重定向到地址。
b)重定向能夠跳轉到當前web應用,或其餘web應用,甚至是外部域名網站。
c)不能再重定向的過程,把數據保存到request中。
結論: 若是要使用request域對象進行數據共享,只能用轉發技術!!!
代碼1:
package com.servlet.context; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class demo1 extends HttpServlet { /** * Constructor of the object. */ public demo1() { super(); } /** * 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 } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // func1(); request.setAttribute("name", "lisi"); this.getServletContext().getRequestDispatcher("/demo2").forward(request, response); } private void func1() { ServletContext context = this.getServletContext(); Student student = new Student("張三", 15, "男"); context.setAttribute("zs", student); } class Student{ private String name; private int age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]"; } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
代碼2:
package com.servlet.context; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.servlet.context.demo1.Student; public class demo2 extends HttpServlet { /** * Constructor of the object. */ public demo2() { super(); } /** * 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 } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // func2(); System.out.println(request.getAttribute("name")); } private void func2() { ServletContext context = this.getServletContext(); Student zs = (Student)context.getAttribute("zs"); System.out.println(zs); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
總結:
Servlet編程:
Servlet生命週期(重點)
其餘都是應用的東西(敲代碼練習)
做業:
改造通信錄程序
servlet+xml版本
要求:
1)使用瀏覽器操做系統
提示:
添加聯繫人:
設計一個添加聯繫人html頁面
保存邏輯:
AddServlet (接收頁面數據(getParameter()),使用dom4j保存到xml)
修改聯繫人
QueryServlet (xml查詢修改的聯繫人, 把聯繫人顯示到一個html頁面(response.getWriter.write("<html></html>")));
修改保存邏輯:
UpdateServlet ( 接收頁面數據,把數據保存xml )
刪除聯繫人:
輸入刪除id的html頁面
刪除邏輯:
DeleteServle( 接收id, 在xml文件中刪除對應的聯繫人)