之前在使用 web.xml配置Servlet時(shí)候出了一些問題,現(xiàn)在大概明白了原因出在哪里。
在這里總結(jié)下當(dāng)時(shí)使用 web.xml配置時(shí)出現(xiàn)的一些問題以及解決的方法
關(guān)鍵點(diǎn)在于兩個(gè):
HTML(JSP)頁面中表單屬性
action的值,以及web.xml中幾個(gè)標(biāo)簽的設(shè)置
- action屬性:
這個(gè)action屬性其實(shí)并沒有具體的意義,只是與web.xml中的<url-pattern></url-pattern>中的值對(duì)應(yīng)即可。但是這里要注意諸如/emailList與emailList這兩種表達(dá)的區(qū)別。之前的虧就吃在這里了。
之前遇到的一個(gè)問題
我在IDEA工程沒有注意到,當(dāng)時(shí)我設(shè)置了<form action="/email" method="post">(我這里有斜杠),在訪問的時(shí)候顯示我訪問到了這個(gè)地址:[http://localhost:8080/email],而我的web.xml設(shè)置如下:
/Task_9_21_war_exploded
<servlet>
<servlet-name>emailListServlet</servlet-name>
<servlet-class>TYUT.emailListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>emailListServlet</servlet-name>
<url-pattern>/email</url-pattern>
</servlet-mapping>
看起來都是正確的,都是匹配的,然而卻顯示 404 NOT FOUND,所以我推測[http://localhost:8080/email]并不是<url-pattern>/email</url-pattern>所代表的地址。
之后我重新設(shè)置:<form action="email" method="post">,然后得到的Servlet訪問地址為:[http://localhost:8080/Task_9_21_war_exploded/email],而此時(shí)正確連接到了Servlet上了。
為什么會(huì)造成這種情況?
后來發(fā)現(xiàn),工程設(shè)置中有這么一條:
工程設(shè)置.PNG
也就是說,我之前設(shè)置了工程的根目錄就是服務(wù)器根目錄下的
/Task_9_21_war_exploded,也就是說我指定了這個(gè)目錄才是這個(gè)項(xiàng)目的根目錄。所以造成了我以為的是根目錄的[http://localhost:8080/email]其實(shí)并不是根目錄。將這個(gè)設(shè)置修改為:設(shè)置2.PNG
此時(shí)安安心心地設(shè)置:<form action="/email" method="post">,就可以正常訪問了。
回到正題
2.使用web.xml配置Servlet的方法:
之前 No.1 那篇里說過web.xml配置,這里再援引一篇講的不錯(cuò)的博客。
https://www.cnblogs.com/fnz0/p/5586019.html
這篇博客講了web.xml的配置以及從表單是如何轉(zhuǎn)到Servlet的具體細(xì)節(jié),很具有參考價(jià)值。
這里提一下博客里提到的跳轉(zhuǎn)過程:
<servlet>
<servlet-name>emailListServlet</servlet-name> //3
<servlet-class>TYUT.emailListServlet</servlet-class> //4
</servlet>
<servlet-mapping>
<servlet-name>emailListServlet</servlet-name> //2
<url-pattern>/email</url-pattern> //1
</servlet-mapping>
- 首先當(dāng)一個(gè)表單請(qǐng)求發(fā)出之后,服務(wù)器首先在web.xml中搜索,找到
1(1的內(nèi)容與表單action屬性相同)
- 找到
1之后,拿著2的值找到3- 找到
3之后,根據(jù)4找到具體的類,然后執(zhí)行類中的doGet和doPost方法