1. 程式人生 > >[Java拾遺三]JavaWeb基礎之Servlet

[Java拾遺三]JavaWeb基礎之Servlet

b- pin dex gets sse throw load 多線程 get

Servlet
1,servlet介紹
servlet是一項動態web資源開發技術.
運行在服務器端.
作用:處理業務邏輯,生成動態的內容,返回給瀏覽器.
本質就是一個類
servlet的入門
1.編寫servlet(類)--- 繼承HttpServlet
2.編寫關系--- web.xml(在WEB-INF下)
3.訪問:
路徑:http://localhost:80/serveltDemo/helloWorld
servlet的體系結構及其常見api
Servlet-- 接口
|
|
GenericServlet---(抽象類)
|
|
HttpServlet--(抽象類)

常用的方法:
servlet的常用方法:
void init(ServletConfig):初始化方法
void service(ServletRequest,ServletResponse):服務--處理業務邏輯
void destroy():銷毀方法

ServletConfig getServletConfig():返回一個servlet的配置對象
String getServletInfo() :返回是servlet一些信息,比如作者 版本

GenericServlet的常用方法:
實現了除了service方法之外的所有方法
init():自己重寫init方法
HttpServlet的常用方法:
service(HttpServletRequest,HttpServletResponse):服務--處理業務邏輯
doGet(HttpServletRequest,HttpServletResponse):處理get請求的
doPost(HttpServletRequest,HttpServletResponse):處理post請求的
代碼示例:

技術分享圖片 HelloServlet.java 技術分享圖片
<servlet-mapping>
       <servlet-name>HelloWroldServlet</servlet-name>
       <url-pattern>/helloWorld</url-pattern>
</servlet-mapping>
   
<servlet>
       <servlet-name>LifeServlet</servlet-name>
       <servlet-class>cn.augmentum.b_life.LifeServlet</servlet-class>
</servlet>     
技術分享圖片

2,servlet生命周期:
生命周期:什麽時候來的,什麽時候走的.
void init(ServletConfig):初始化方法
* 執行時間:默認情況來說,第一次的請求的時候執行
* 執行次數:一次
* 執行者:tomcat
void service(ServletRequest,ServletResponse):服務--處理業務邏輯
* 執行時間:有請求就執行
* 執行次數:請求一次,執行一次
* 執行者:tomcat
void destroy():銷毀方法
* 執行時間:服務器正常關閉的時候執行
* 執行次數:一次
* 執行者:tomcat
servlet是單實例多線程的
默認的情況下是第一次訪問的時候創建(有服務器創建),每出現一次請求,創建一個線程,用來處理請求,
直到服務器正常關閉或者項目移除的時候servlet銷毀
url-pattern編寫

1.完全匹配,----(servlet最常用的)以"/"開頭
例如:/a/b/c/hello
2.目錄匹配 以"/"開頭,以"*"結尾(filter常用的)
例如:/a/*
3.後綴名匹配 以"*"開頭
例如: *.do *.jsp

優先級:
完全匹配>目錄匹配>後綴名匹配

有如下的一些映射關系:
Servlet1 映射到 /abc/*
Servlet2 映射到 /*
Servlet3 映射到 /abc
Servlet4 映射到 *.do
問題:
當請求URL為“/abc/a.html”,“/abc/*”和“/*”都匹配,哪個servlet響應
Servlet引擎將調用Servlet1。
當請求URL為“/abc”時,“/abc/*”和“/abc”都匹配,哪個servlet響應
Servlet引擎將調用Servlet3。
當請求URL為“/abc/a.do”時,“/abc/*”和“*.do”都匹配,哪個servlet響應
Servlet引擎將調用Servlet1。
當請求URL為“/a.do”時,“/*”和“*.do”都匹配,哪個servlet響應
Servlet引擎將調用Servlet2.
當請求URL為“/xxx/yyy/a.do”時,“/*”和“*.do”都匹配,哪個servlet響應
Servlet引擎將調用Servlet2。
tomcat的defalutservlet處理別的servlet處理不了的請求.
load-on-startup
在servlet標簽下
改變servlet初始化時機.
若值>=0的時候,servlet會隨著服務器的啟動而創建.
值越小,優先級越高
瀏覽器的路徑編寫:
1.瀏覽器直接輸入
2.a標簽
3.location.href
4.表單提交

路徑的寫法:
1.絕對路徑
帶協議的絕對路徑--一般訪問站外資源的時候用
http://localhost:80/servletDemo/helloWorld
不帶協議的絕對路徑--站內資源
/servletDemo/helloWorld
2.相對路徑
./(路徑) 和 ../
八字方針
當前路徑 http://localhost/servletDemo/ index.html
訪問路徑 http://localhost/servletDemo/ demoa

當前路徑 http://localhost/servletDemo/ a/b/c ../../demoa
訪問路徑 http://localhost/servletDemo/ demoa
以後使用的是絕對路徑(一般使用的是不帶協議的絕對路徑)

3,ServletConfig
他是當前servlet的配置對象.
獲取方式:
ServletConfig config=this.getServletConfig();
作用:
1.可以獲取到當前servlet初始化參數
2.可以獲得全局管理者
常用方法:
String getServletName():獲取當前servlet的名稱 --指的是web.xml中servlet名字
String getInitParameter(name):獲取指定的參數
Enumeration getInitParameterNames():獲取全部初始化參數名稱

ServletContext getServletContext():獲取全局管理者
當servlet初始化的時候,執行了init(ServletConfig config),就把創建好的servletConfig傳給了servlet
由tomcat創建

示例代碼:

技術分享圖片 技術分享圖片
 1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2     ServletConfig conf=this.getServletConfig();
 3     //獲取當前servlet名字
 4     String name=conf.getServletName();
 5     System.out.println(name);
 6     
 7     //獲取名字為 "姓名"的參數值
 8     String value = conf.getInitParameter("姓名");
 9     System.out.println(value);
10     
11     //獲取全部參數名稱
12     Enumeration<String> names=conf.getInitParameterNames();
13     while(names.hasMoreElements()){
14         String name_=names.nextElement();
15         System.out.println(name_+":"+conf.getInitParameter(name_));
16     }
17 }
技術分享圖片



4,ServletContext
全局管理者.
每個應用在tomcat啟動的時候,就會創建一個servletcontext對象,這個對象可以獲取到當前應用的所有信息,實現資源共享.
本質servletcontext就是對當前應用的一個引用.
作用:
1.實現資源共享
2.獲取全局初始化參數.
3.獲取資源.
怎麽獲取:
this.getServletConfig().getServletContext():
getServletContext()也可以獲取
常見的方法:
String getInitparameter(name);獲取指定的參數
Enumeration getInitParameterNames():獲取全部的參數名稱
參數
<context-param>
<param-name>
<param-value>

String getRealPath(path):返回相應文件在tomcat的實際路徑
例如:D:\JavaTools\apache-tomcat-7.0.53\webapps\servletDemo\
InputStream getResourceAsStream(String path) :以流的形式返回對應的文件.

String getMimeType(String file) 可以獲取一個文件的mimeType類型. 例如 text/html
URL getResource(String path) 它返回的是一個資源的URL 例如: localhost/day09/a.html
域對象:
把他看成一個map,
xxxAttribute()
setAttribute(String,Object):添加
Object getAttribute(string):獲取
removeAttribute(string):移除
示例代碼:

技術分享圖片 技術分享圖片
 1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2     //首先獲取ServletContext對象
 3     ServletContext context=this.getServletContext();
 4     
 5     //獲取url
 6     String url=context.getInitParameter("url");
 7     //System.out.println(url);
 8     
 9     //獲取全部的全局初始化參數
10     Enumeration<String> paramNames=context.getInitParameterNames();
11     while(paramNames.hasMoreElements()){
12         String name=paramNames.nextElement();
13         ///System.out.println(name+":"+context.getInitParameter(name));
14     }
15     
16     //返回 "/"的路徑
17     //String path=context.getRealPath("/");
18     //String path = context.getRealPath("/5.txt"); // 錯誤的
19     //System.out.println(path);
20     /*InputStream in = context.getResourceAsStream("/WEB-INF/classes/cn/itcast/e_servletcontext/5.txt");
21     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
22     String readLine = reader.readLine();
23     System.out.println(readLine);*/
24     
25     //獲取index.htmlmime類型
26     
27     String type = context.getMimeType("/a.html");
28     //System.out.println(type);
29     URL url_ = context.getResource("/a.html");
30     System.out.println(url_.getPath());
31 }
技術分享圖片

5,classpath
獲取字節碼文件的路徑.
通過字節碼文件獲取
當前類.class.getResource("/").getPath():返回classes的目錄
D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
當前類.class.getResource("").getPath():返回當前類的字節碼文件所在的目錄
D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/cn/itcast/h_classpath/

通過類加載器獲取文件路徑
當前類.class.getClassLoader().getResource("/").getPath():返回classes的目錄
D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
當前類.class.getClassLoader().getResource().getPath():返回classes的目錄
D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
示例代碼:

技術分享圖片 技術分享圖片
 1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2     //String path1 = PathServlet.class.getResource("/").getPath();
 3     // D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
 4     //String path2 = PathServlet.class.getResource("").getPath();
 5     // D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/cn/augmentum/h_classpath/
 6     // System.out.println(path1);
 7     // System.out.println(path2);
 8 
 9     //String path3 = PathServlet.class.getClassLoader().getResource("/").getPath();
10     //String path4 = PathServlet.class.getClassLoader().getResource("").getPath();
11 
12     //System.out.println(path3);
13     //System.out.println(path4);
14     //       myeclipse                         tomcat路徑                                             獲取
15     //1.txt  src                            /WEB-INF/classes/1.txt                            lei.class.getResource("/").getpath()
16     //2.txt  webroot                        /2.txt                                            context.getRealPath
17     //3.txt  web-inf                        /WEB-INF/3.txt                                    context.getRealPath
18     //4.txt  cn.augmentum.h_classpath            /WEB-INF/classes/cn/augmentum/h_classpath/4.txt    lei.class.getResource("").getpath()
19     
20     ServletContext context=this.getServletContext();
21     String path1 = PathServlet.class.getResource("/1.txt").getPath();
22     String path2 = context.getRealPath("/2.txt");
23     String path3 = context.getRealPath("/WEB-INF/3.txt");
24     String path4 = PathServlet.class.getResource("4.txt").getPath();
25     
26     /*System.out.println(path1);
27     System.out.println(path2);
28     System.out.println(path3);
29     System.out.println(path4);*/
30     readFile(path1);
31     readFile(path2);
32     readFile(path3);
33     readFile(path4);
34 }
技術分享圖片


小demo: 當訪問index.html中的 鏈接則通過CountServlet計數, 每訪問一次則count加1, 然後通過ShowServlet展示到控制臺:

技術分享圖片 技術分享圖片
 1 public class CountServlet extends HttpServlet {
 2 
 3     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 4         //訪問計數
 5         //首先獲取context對象
 6         ServletContext context=this.getServletContext();
 7         //請求一次,context取出訪問次數
 8         Integer count=(Integer) context.getAttribute("count");
 9         //次數+1,放入context中
10         if (count==null) {
11             context.setAttribute("count", 1);
12         }else{
13             context.setAttribute("count", ++count);
14         }
15     }
16 
17     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         doGet(request, response);
19     }
20 
21 }
技術分享圖片 技術分享圖片 技術分享圖片
 1 public class ShowServlet extends HttpServlet {
 2 
 3     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 4         //首先獲取context
 5         ServletContext context=this.getServletContext();
 6         //取次數
 7         Integer count=(Integer) context.getAttribute("count");
 8         System.out.println("訪問的次數為:"+(count==null?0:count));
 9     }    
10 
11     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
12         doGet(request, response);
13     }
14 
15 }
技術分享圖片 技術分享圖片
1 <body>
2     <a href="/servletDemo/count">顯示次數</a><br/>
3     <a href="/servletDemo/show">展示結果</a><br/>
4 </body>
技術分享圖片 技術分享圖片
 1 <servlet>
 2     <servlet-name>CountServlet</servlet-name>
 3     <servlet-class>cn.augmentum.showcount.CountServlet</servlet-class>
 4 </servlet>
 5 <servlet>
 6     <servlet-name>ShowServlet</servlet-name>
 7     <servlet-class>cn.augmentum.showcount.ShowServlet</servlet-class>
 8 </servlet>
 9 <servlet-mapping>
10     <servlet-name>CountServlet</servlet-name>
11     <url-pattern>/count</url-pattern>
12 </servlet-mapping>
13 <servlet-mapping>
14     <servlet-name>ShowServlet</servlet-name>
15     <url-pattern>/show</url-pattern>
16 </servlet-mapping>
技術分享圖片

[Java拾遺三]JavaWeb基礎之Servlet