java servlet_Java Servlet的前100个问题
java servlet
1)是“ servlets”目錄還是“ servlet”目錄?
回答:
對于Java Web Server:
- 在文件系統(tǒng)上,它是“ servlet”
c:\ JavaWebServer1.1 \ servlets \ DateServlet.class
- 在URL路徑中,它是“ servlet”: http : //www.stinky.com/servlet/DateServlet
2)如何從同一個Servlet支持GET和POST協(xié)議?
回答:
簡單的方法是,僅支持POST,然后讓您的doGet方法調(diào)用您的doPost方法:
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{doPost(req, res);}3)如何確保我的servlet是線程安全的?
回答:
這實(shí)際上是一個非常復(fù)雜的問題。 一些準(zhǔn)則:
(請注意,如果您使用新名稱(例如新的init參數(shù))注冊servlet,服務(wù)器還將分配新的實(shí)例。)
另請參閱啟用線程安全的servlet和JSP的更好方法是什么? SingleThreadModel接口還是同步?
4)URL編碼,URL重寫,HTML轉(zhuǎn)義和實(shí)體編碼之間有什么區(qū)別?
回答:
URL編碼
是將用戶輸入轉(zhuǎn)換為CGI表單的過程,因此適合于跨網(wǎng)絡(luò)旅行-基本上是刪除空格和標(biāo)點(diǎn)符號,并以轉(zhuǎn)義字符代替。 URL解碼是相反的過程。 要執(zhí)行這些操作,請調(diào)用java.net.URLEncoder.encode()和java.net.URLDecoder.decode()(后者已(最終!)添加到了JDK 1.2(又名Java 2)中)。
例:
更改“我們是第一!” 變成“我們%27re +%231%21”
URL重寫
是一種在兩次頁面點(diǎn)擊之間將狀態(tài)信息保存在用戶瀏覽器上的技術(shù)。 有點(diǎn)像cookie,只是信息被存儲在URL中,作為附加參數(shù)。 HttpSession API是Servlet API的一部分,有時在cookie不可用時會使用URL重寫。
例:
將<A HREF=”nextpage.html”>更改為
<A HREF=”nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE”>(或?qū)嶋H語法是什么;我忘記了)(不幸的是,Servlet API中用于為會話管理進(jìn)行URL重寫的方法稱為encodeURL()。嘆…)
Apache Web服務(wù)器還有一個名為URL Rewriting的功能。 它由mod_rewrite模塊啟用。 它會在進(jìn)入服務(wù)器的過程中重寫URL,從而使您可以執(zhí)行以下操作,例如將斜杠自動添加到目錄名,或?qū)⑴f文件名映射到新文件名。 這與servlet無關(guān)。
5)如何將文件上傳到我的servlet或JSP?
回答:
在客戶端,客戶端的瀏覽器必須支持基于表單的上傳。 大多數(shù)現(xiàn)代瀏覽器都可以,但是不能保證。 例如,
<FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'><INPUT TYPE='file' NAME='mptest'><INPUT TYPE='submit' VALUE='upload'></FORM>輸入類型“文件”被指定為“文件”。 會在瀏覽器上彈出一個用于文件選擇框的按鈕,并帶有一個文本字段,該文本字段一旦選定即取文件名。 當(dāng)請求的POST正文包含要解析的文件數(shù)據(jù)時,Servlet可以使用GET方法參數(shù)來決定如何處理上傳。
當(dāng)用戶單擊“上傳”按鈕時,客戶端瀏覽器將找到本地文件并使用HTTP POST發(fā)送該文件,該文件使用MIME類型的multipart / form-data進(jìn)行編碼。 當(dāng)它到達(dá)您的servlet時,您的servlet必須處理POST數(shù)據(jù)以便提取編碼的文件。 您可以在RFC 1867中了解有關(guān)此格式的所有信息。
不幸的是,Servlet API中沒有方法可以做到這一點(diǎn)。 幸運(yùn)的是,有許多可用的庫。 其中一些假設(shè)您將把文件寫入磁盤。 其他人將數(shù)據(jù)作為InputStream返回。
- Jason Hunter的MultipartRequest (可從http://www.servlets.com/獲得 )
- Apache Jakarta Commons Upload (軟件包org.apache.commons.upload)“使向Servlet和Web應(yīng)用程序添加強(qiáng)大的高性能文件上傳功能變得容易”
- CParseRFC1867(可從http://www.servletcentral.com/獲得 )。
- Anav Hemrajani的HttpMultiPartParser ,在isavvix代碼交換處
- 在http:// www-的 Anders Kristensen( http://www-uk.hpl.hp.com/people/ak/java/ ak@hplb.hpl.hp.com )上有一個multipart / form解析器。 uk.hpl.hp.com/people/ak/java/#utils 。
- JavaMail還具有MIME解析例程(請參見Purple Servlet References )。
- Jun Inamori編寫了一個名為org.apache.tomcat.request.ParseMime的類,該類在Tomcat CVS樹中可用。
- JSPSmart提供了一組免費(fèi)的JSP,用于執(zhí)行文件上傳和下載。
- JavaZoom的UploadBean聲稱可以為您處理大部分的上傳麻煩,包括寫入磁盤或內(nèi)存。
- dotJ中有一個上傳標(biāo)簽
將表單數(shù)據(jù)流處理為上載的文件后,您可以根據(jù)需要將其寫入磁盤,將其寫入數(shù)據(jù)庫或作為InputStream處理。 請參閱如何從servlet內(nèi)部訪問或在當(dāng)前目錄中創(chuàng)建文件或文件夾? Servlets:Files主題中的其他問題以及有關(guān)從Servlet寫入文件的信息。
請注意 ,您不能直接從servlet訪問客戶端系統(tǒng)上的文件; 那將是一個巨大的安全漏洞。 您必須征詢用戶的許可,當(dāng)前基于表單的上傳是唯一的方式。
6)servlet如何與JSP頁面通信?
回答:
以下代碼段顯示了servlet如何實(shí)例化bean并使用瀏覽器發(fā)布的FORM數(shù)據(jù)對其進(jìn)行初始化。 然后將bean放入請求中,然后通過請求分派器將調(diào)用轉(zhuǎn)發(fā)到JSP頁面Bean1.jsp,以進(jìn)行下游處理。
public void doPost (HttpServletRequest request,HttpServletResponse response) {try {govi.FormBean f = new govi.FormBean();String id = request.getParameter("id");f.setName(request.getParameter("name"));f.setAddr(request.getParameter("addr"));f.setAge(request.getParameter("age"));//use the id to compute//additional bean properties like info//maybe perform a db query, etc.// . . .f.setPersonalizationInfo(info);request.setAttribute("fBean",f);getServletConfig().getServletContext().getRequestDispatcher("/jsp/Bean1.jsp").forward(request, response);} catch (Exception ex) {. . .}}在首先通過useBean操作從默認(rèn)請求范圍中提取fBean之后,JSP頁面Bean1.jsp可以處理fBean。
<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/><jsp:getProperty name="fBean" property="name" /><jsp:getProperty name="fBean" property="addr" /><jsp:getProperty name="fBean" property="age" /><jsp:getProperty name="fBean" property="personalizationInfo" />SingleThreadModel接口還是同步?
回答:
盡管SingleThreadModel技術(shù)易于使用,并且在低容量站點(diǎn)上效果很好,但是它的伸縮性不好。 如果您希望用戶將來會增加,那么最好對共享數(shù)據(jù)實(shí)施顯式同步。 但是,關(guān)鍵是有效地最小化已同步的代碼量,以便最大程度地利用多線程。
另外,請注意,從服務(wù)器的角度來看,SingleThreadModel占用大量資源。 但是,最嚴(yán)重的問題是并發(fā)請求數(shù)耗盡了servlet實(shí)例池。 在這種情況下,所有未服務(wù)的請求都將排隊(duì)等待,直到有空閑的東西為止–這會導(dǎo)致性能下降。 由于使用情況不確定,因此即使您確實(shí)增加了內(nèi)存并增加了實(shí)例池的大小,也可能無濟(jì)于事。
8)一個servlet可以在多個servlet調(diào)用之間維護(hù)JTA UserTransaction對象嗎?
回答:
不能。JTA事務(wù)必須在一次調(diào)用(對service()方法)中開始和完成。 請注意,此問題并未解決維護(hù)和操作JDBC連接(包括連接的事務(wù)處理)的servlet。
它與Perl腳本相比如何?
回答:
JSP頁面的性能非常接近servlet。 但是,當(dāng)?shù)谝淮卧L問JSP頁面時,用戶可能會遇到明顯的延遲。 這是因?yàn)镴SP頁面經(jīng)歷了“翻譯階段”,在此階段,JSP頁面將其轉(zhuǎn)換為servlet。 一旦該Servlet被動態(tài)編譯并加載到內(nèi)存中,它就會遵循Servlet生命周期進(jìn)行請求處理。 在此,JSP引擎在加載servlet時會自動調(diào)用jspInit()方法,然后是_jspService()方法,該方法負(fù)責(zé)處理請求并回復(fù)客戶端。 請注意,此Servlet的生存期是不確定的–出于資源相關(guān)的原因,JSP引擎可隨時將其從內(nèi)存中刪除。 發(fā)生這種情況時,JSP引擎會自動調(diào)用jspDestroy()方法,從而允許Servlet釋放任何先前分配的資源。
只要Servlet緩存在內(nèi)存中,隨后對JSP頁面的客戶端請求就不會重復(fù)轉(zhuǎn)換階段,而是由Servlet的service()方法以并發(fā)方式直接處理(即,service()方法處理每個客戶請求同時在單獨(dú)的線程中)。
最近有一些研究將Servlet的性能與在“真實(shí)”環(huán)境中運(yùn)行的Perl腳本進(jìn)行了對比。 結(jié)果對Servlet有利,尤其是當(dāng)它們在集群環(huán)境中運(yùn)行時。
10)如何從另一個servlet調(diào)用一個servlet?
回答:
[簡短答案:有幾種方法可以做到這一點(diǎn),包括
- 使用RequestDispatcher
- 使用URLConnection或HTTPClient
- 發(fā)送重定向
- 調(diào)用getServletContext()。getServlet(name)(不建議使用,在2.1+版本中不起作用)
–亞歷克斯]
這取決于您所說的“通話”的含義,您想要做什么以及為什么要這么做。
如果最終的結(jié)果是調(diào)用方法,那么最簡單的機(jī)制就是將servlet像任何java對象一樣對待,創(chuàng)建一個實(shí)例并調(diào)用該方法。
如果想法是從另一個servlet的服務(wù)方法中調(diào)用服務(wù)方法,即轉(zhuǎn)發(fā)請求,則可以使用RequestDispatcher對象。
但是,如果要訪問由servlet引擎加載到內(nèi)存中的servlet實(shí)例,則必須知道servlet的別名。 (如何定義它取決于引擎。)例如,要在JSDK中調(diào)用servlet,可以通過該屬性來命名servlet。
myname.code=com.sameer.servlets.MyServlet下面的代碼顯示了如何在另一個servlet的service方法中訪問這個命名的servlet。
public void service (HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {...MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname");...}就是說,由于安全性問題,在Servlet API的2.1版本中已棄用了在另一個Servlet中訪問Servlet的整個方法。 更干凈,更好的方法是避免直接訪問其他servlet,而使用RequestDispatcher。
(例如Web服務(wù)器,應(yīng)用程序服務(wù)器等)
回答:
涉及處理和處理用戶請求的服務(wù)器分為幾種基本類型,每種基本類型都可以解決一個或多個任務(wù)。 這種靈活性為開發(fā)人員提供了在如何創(chuàng)建和部署應(yīng)用程序方面的強(qiáng)大功能,但也導(dǎo)致對服務(wù)器能夠或應(yīng)該執(zhí)行特定任務(wù)的困惑。
從基本級別開始,用戶通常是通過Web瀏覽器向系統(tǒng)提交請求。 (為了清楚起見,我們暫時忽略了所有其他類型的客戶端(RMI,CORBA,COM / DCOM,自定義等)。)Web請求必須由Web服務(wù)器接收(否則稱為Web服務(wù)器)。 HTTP Server )。 該Web服務(wù)器必須處理標(biāo)準(zhǔn)的HTTP請求和響應(yīng),通常將HTML返回給調(diào)用用戶。 在服務(wù)器環(huán)境中執(zhí)行的代碼可能是CGI驅(qū)動的,Servlet,ASP或某些其他服務(wù)器端編程語言,但是最終結(jié)果是Web服務(wù)器將HTML返回給用戶。
Web服務(wù)器可能需要響應(yīng)用戶請求執(zhí)行應(yīng)用程序。 它可能正在生成新聞列表,或者處理向訪客留言簿的表單提交。 如果服務(wù)器應(yīng)用程序是用Java Servlet編寫的,它將需要一個執(zhí)行位置,該位置通常稱為Servlet Engine 。 取決于Web服務(wù)器,此引擎可以是內(nèi)部,外部或完全不同的產(chǎn)品。 該引擎一直在運(yùn)行,這與傳統(tǒng)的CGI環(huán)境不同,在傳統(tǒng)的CGI環(huán)境中,每次向服務(wù)器發(fā)出請求時都會啟動CGI腳本。 這種持久性提供了Servlet連接和線程池,以及維護(hù)每個HTTP請求之間狀態(tài)的簡便方法。 JSP頁面通常與servlet引擎綁定在一起,并且將在與servlet相同的空間/應(yīng)用程序中執(zhí)行。
有許多產(chǎn)品以不同的方式處理Web服務(wù)和Servlet引擎。 Netscape / iPlanet Enterprise Server將Servlet引擎直接構(gòu)建到Web服務(wù)器中,并在同一進(jìn)程空間中運(yùn)行。 Apache要求Servlet引擎在外部進(jìn)程中運(yùn)行,并且將通過TCP / IP套接字與該引擎進(jìn)行通信。 其他服務(wù)器(例如MS IIS)并不正式支持servlet,并且需要附加產(chǎn)品才能添加該功能。
當(dāng)您繼續(xù)使用Enterprise JavaBeans(以及其他J2EE組件,例如JMS和CORBA)時,您將進(jìn)入應(yīng)用程序服務(wù)器空間。 應(yīng)用程序服務(wù)器是任何提供與企業(yè)計(jì)算相關(guān)的附加功能的服務(wù)器,例如,負(fù)載平衡,數(shù)據(jù)庫訪問類,事務(wù)處理,消息傳遞等。
EJB應(yīng)用服務(wù)器提供了一個EJB容器,bean將在該容器中執(zhí)行該環(huán)境,并且該容器將根據(jù)需要管理事務(wù),線程池和其他問題。 這些應(yīng)用程序服務(wù)器通常是獨(dú)立產(chǎn)品,開發(fā)人員可以通過遠(yuǎn)程對象訪問API將其servlet / JSP頁面綁定到EJB組件。 根據(jù)應(yīng)用服務(wù)器的不同,程序員可以使用CORBA或RMI與他們的bean進(jìn)行通信,但是基本標(biāo)準(zhǔn)是根據(jù)需要使用JNDI定位和創(chuàng)建EJB引用。
現(xiàn)在,使這個問題困惑的一件事是,許多應(yīng)用程序服務(wù)器提供程序在其產(chǎn)品中都包含了部分或全部這些組件。 如果查看WebLogic(http://www.beasys.com/),則會發(fā)現(xiàn)WebLogic包含Web服務(wù)器,Servlet引擎,JSP處理器,JMS工具以及EJB容器。 從理論上講,此類產(chǎn)品可用于處理站點(diǎn)開發(fā)的所有方面。 實(shí)際上,您很可能會使用這種類型的產(chǎn)品來管理/服務(wù)EJB實(shí)例,而專用的Web服務(wù)器則處理特定的HTTP請求。
12)我應(yīng)該重寫service()方法嗎?
回答:
不。它提供了很多您只需要自己做的內(nèi)務(wù)處理。 如果無論請求是POST還是GET都需要做某事,請創(chuàng)建一個輔助方法,并在doPost()和doGet()的開頭調(diào)用它。
13)我的應(yīng)用程序如何知道刪除HttpSession的時間(超時)?
回答:
定義一個類,例如SessionTimeoutNotifier,它實(shí)現(xiàn)javax.servlet.http.HttpSessionBindingListener。 創(chuàng)建一個SessionTimeoutNotifier對象,并將其添加到用戶會話中。 刪除會話后,Servlet引擎將調(diào)用SessionTimeoutNotifier.valueUnbound()。 您可以實(shí)現(xiàn)valueUnbound()來做任何您想做的事情。
14)當(dāng)我們可以對servlet執(zhí)行相同的操作時,為什么要使用JSP?
[原始問題:當(dāng)已經(jīng)有servlet技術(shù)可用于提供動態(tài)內(nèi)容時,為什么我應(yīng)該使用JSP?]
回答:
盡管JSP可以很好地提供動態(tài)Web內(nèi)容并將內(nèi)容與表示分離,但有些人可能仍想知道為什么應(yīng)將servlet拋給JSP。 servlet的實(shí)用程序不成問題。 它們非常適合服務(wù)器端處理,并且由于其龐大的安裝基礎(chǔ),因此可以保留。 實(shí)際上,從架構(gòu)上來講,您可以將JSP視為Servlet的高級抽象,它是Servlet 2.1 API的擴(kuò)展而實(shí)現(xiàn)的。 不過,您不應(yīng)該隨意使用servlet。 它們可能并不適合所有人。 例如,盡管頁面設(shè)計(jì)人員可以使用常規(guī)HTML或XML工具輕松編寫JSP頁面,但servlet更適合于后端開發(fā)人員,因?yàn)樗鼈兺ǔJ褂肐DE編寫-該過程通常需要更高水平的編程專業(yè)知識。
在部署servlet時,即使開發(fā)人員也必須小心,并確保表示和內(nèi)容之間沒有緊密的聯(lián)系。 通常,您可以通過在混合中添加第三方HTML包裝程序包(例如htmlKona)來實(shí)現(xiàn)此目的。 但是,即使采用這種方法,盡管可以通過簡單的屏幕更改提供一定的靈活性,但仍然不能阻止您更改演示格式本身。 例如,如果您的演示文稿從HTML更改為DHTML,則仍然需要確保包裝程序包與新格式兼容。 在最壞的情況下,如果沒有包裝程序包,則最終可能會在動態(tài)內(nèi)容中對表示進(jìn)行硬編碼。 那么,解決方案是什么? 一種方法是同時使用JSP和Servlet技術(shù)來構(gòu)建應(yīng)用程序系統(tǒng)。
15)如何使用HTTP協(xié)議在applet和servlet之間來回發(fā)送信息和數(shù)據(jù)?
回答:
使用標(biāo)準(zhǔn)的java.net.URL類,或使用java.net.Socket“自行滾動”。 請參閱HTTP規(guī)范
有關(guān)詳細(xì)信息,請?jiān)L問W3C。
注意: Servlet無法啟動該連接! 如果servlet需要異步將消息發(fā)送到applet,則必須使用java.net.Socket(在applet端)以及java.net.ServerSocket和Threads(在服務(wù)器端)打開持久套接字。
16)是否可以獲取當(dāng)前servlet在文件系統(tǒng)上的路徑(不是URL)?
回答:
嘗試使用:
request.getRealPath(request.getServletPath())一個示例可能是:
out.println(request.getRealPath(request.getServletPath()));17)如何將servlet菊花鏈在一起,以使一個servlet的輸出成為下一個的輸入?
回答:
有兩種常見的方法將一個servlet的輸出鏈接到另一個servlet:
要將servlet鏈接在一起,必須指定servlet的順序列表,并將其與別名關(guān)聯(lián)。 當(dāng)對該別名發(fā)出請求時,將調(diào)用列表中的第一個servlet,處理其任務(wù),并將輸出作為請求對象發(fā)送到列表中的下一個servlet。 輸出可以再次發(fā)送到另一個servlet。
要實(shí)現(xiàn)此方法,您需要配置servlet引擎(JRun,JavaWeb服務(wù)器,JServ…)。
例如,要為Servlet鏈接配置JRun,請選擇JSE服務(wù)(JRun Servlet引擎)以訪問“ JSE服務(wù)配置”面板。 您只需要定義一個新的映射規(guī)則,即可在其中定義鏈接servlet。
假設(shè)使用/ servlets / chainServlet表示虛擬路徑,并用逗號分隔servlet列表,如srvA,srvB。
因此,當(dāng)您調(diào)用諸如http:// localhost / servlets / chainServlet之類的請求時,將首先在內(nèi)部調(diào)用servlet srvA,并將其結(jié)果傳遞到servlet srvB中。
srvA servlet代碼應(yīng)如下所示:
public class srvA extends HttpServlet {...public void doGet (...) {PrintWriter out =res.getWriter();rest.setContentType("text/html");...out.println("Hello Chaining servlet");}}servlet srvB所要做的就是打開請求對象的輸入流,并將數(shù)據(jù)讀入BufferedReader對象,例如:
BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) );String data = b.readLine();b.close();之后,您可以使用數(shù)據(jù)格式化輸出。
它也應(yīng)該可以與Java Web Server或Jserv一起使用。 只需查看他們的文檔即可定義別名。 希望對您有所幫助。
18)為什么servlet中沒有構(gòu)造函數(shù)?
回答:
就其具有充當(dāng)構(gòu)造函數(shù)的init()方法而言,Servlet就像小應(yīng)用程序一樣。 由于servlet環(huán)境負(fù)責(zé)實(shí)例化servlet,因此不需要顯式的構(gòu)造函數(shù)。 您需要運(yùn)行的任何初始化代碼都應(yīng)放在init()方法中,因?yàn)樗窃赟ervlet容器首次加載Servlet時被調(diào)用的。
19)將JDBC與Servlet一起使用時,如何處理多個并發(fā)數(shù)據(jù)庫請求/更新?
回答:
每當(dāng)修改數(shù)據(jù)時,所有的dbms都提供鎖定功能。 可能有兩種情況:
JDBC文檔中處理了此問題。 查找“交易”和“自動提交”。 可能會造成混亂。
20)GenericServlet和HttpServlet有什么區(qū)別?
回答:
GenericServlet適用于可能不使用HTTP的Servlet,例如FTP Servlet。 當(dāng)然,事實(shí)證明沒有FTP servlet這樣的東西,但是他們在設(shè)計(jì)規(guī)范時正試圖為將來的增長做計(jì)劃。 也許有一天會有另一個子類,但是現(xiàn)在,始終使用HttpServlet。
21)如何在Servlet和JSP之間共享會話對象?
回答:
直接在servlet和JSP頁面之間共享會話。 JSP通過創(chuàng)建會話對象并使其變得可用來使其變得容易一些。 在servlet中,您必須自己做。 這是這樣的:
//create a session if one is not created already nowHttpSession session = request.getSession(true);//assign the session variable to a value.session.putValue("variable","value");在jsp頁面中,這是獲取會話值的方法:
<%session.getValue("varible");%>22)什么是servlet?
回答:
Servlet是使用Java程序擴(kuò)展Web服務(wù)器以執(zhí)行以前由CGI腳本或?qū)S蟹?wù)器擴(kuò)展框架處理的任務(wù)的一種方式。
23)是否有什么方法可以在不重新啟動服務(wù)器的情況下從Web服務(wù)器內(nèi)存中卸載servlet?
回答:
沒有標(biāo)準(zhǔn)的方法/機(jī)制可以從內(nèi)存中卸載servlet。 某些服務(wù)器(例如JWS)提供了從其管理模塊加載和卸載servlet的方法。 其他人(例如Tomcat)要求您僅替換WAR文件。
24)JavaBean和Servlet有什么區(qū)別?
回答:
JavaBeans是創(chuàng)建可重用的軟件組件或bean遵循的一組規(guī)則。 這包含屬性和事件。 最后,您有了一個可由程序(例如IDE)檢查的組件,以允許JavaBean組件的用戶對其進(jìn)行配置并在其Java程序中運(yùn)行。
Servlet是在Servlet引擎中運(yùn)行的Java類,實(shí)現(xiàn)了特定的接口:Servlet,強(qiáng)制您實(shí)施某些方法(service())。 servlet是運(yùn)行該servlet的Web服務(wù)器的擴(kuò)展,僅當(dāng)用戶請求從網(wǎng)頁到servlet的GET或POST調(diào)用時才通知您。
因此,除了Java之外,兩者都沒有共同點(diǎn)。
25)我們可以在一個會話對象中存儲多少數(shù)據(jù)?
回答:
由于會話保留在服務(wù)器端,因此可以在其中存儲任何數(shù)量的數(shù)據(jù)。
唯一的限制是sessionId長度,該長度不得超過?4000字節(jié)-HTTP標(biāo)頭長度限制為4Kb暗示了此限制,因?yàn)閟essionId可能存儲在cookie中或以URL編碼(使用“ URL rewriting ”)和cookie規(guī)范表示Cookie和HTTP請求(例如GET /document.html\n)的大小不能超過4kb。
26)doGet和doPost方法之間有什么區(qū)別?
回答:
調(diào)用doGet以響應(yīng)HTTP GET請求。 當(dāng)用戶單擊鏈接或在瀏覽器的地址欄中輸入URL時,會發(fā)生這種情況。 對于某些HTML FORM(在FORM標(biāo)記中指定了METHOD =“ GET”HTML FORM),也會發(fā)生這種情況。
調(diào)用doPost以響應(yīng)HTTP POST請求。 某些HTML FORM(在FORM標(biāo)記中指定了METHOD =“ POST”HTML FORM)會發(fā)生這種情況。
HttpServlet基類中的服務(wù)的默認(rèn)(超類)實(shí)現(xiàn)調(diào)用這兩種方法。 您應(yīng)該覆蓋一個或兩個來執(zhí)行servlet的動作。 您可能不應(yīng)該重寫service()。
27)encodeRedirectUrl和encodeURL有什么區(qū)別?
回答:
encodeURL和encodeRedirectURL是HttpResponse對象的方法。 如有必要,兩者都重寫原始URL以包括會話數(shù)據(jù)。 (如果啟用了cookie,則兩個都不操作。)
encodeURL用于HTML頁面內(nèi)的普通鏈接。
encodeRedirectURL用于傳遞給response.sendRedirect()的鏈接。 它的語法要求也略有不同,因此不適合在這里使用。
28)我可以在servlet中使用System.exit()嗎?
回答:
加油! 不,不,不,不...
充其量,您將獲得一個安全例外。 最糟糕的是,您將使servlet引擎或整個Web服務(wù)器退出。 你真的不想那樣做,對吧?
我是否需要在Connection或Statement對象上進(jìn)行同步?
回答:
您不必。 如果您的JDBC驅(qū)動程序支持多個連接,那么即使其他請求/線程也正在訪問同一連接上的其他語句,各種createStatement方法也將為您提供一個線程安全,可重入,獨(dú)立的語句,該語句應(yīng)該可以正常運(yùn)行。
當(dāng)然,雙手合十永遠(yuǎn)不會受傷……許多早期的JDBC驅(qū)動程序并沒有重入。 現(xiàn)代版本的JDBC驅(qū)動程序應(yīng)該可以正常運(yùn)行,但是永遠(yuǎn)不能保證。
使用連接池可以避免整個問題,并且可以提高性能。
30)如何確定正在使用的servlet或JSP引擎的名稱和版本號?
回答:
在Servlet中,您可以按以下方式調(diào)用ServletContext.getServerInfo()方法:
String thisServer= getServletConfig().getServletContext().getServerInfo();如果使用的是JSP,則可以使用以下表達(dá)式:
<%= application.getServerInfo() %>31)如何在運(yùn)行時獲取servlet / JSP頁面的絕對URL?
回答:
您可以獲取所有必要信息,以便從請求對象確定URL。 要從方案,服務(wù)器名稱,端口,URI和查詢字符串重構(gòu)絕對URL,可以使用java.net中的URL類。 以下代碼片段將確定您頁面的絕對URL:
String file = request.getRequestURI();if (request.getQueryString() != null) {file += '?' + request.getQueryString();}URL reconstructedURL = new URL(request.getScheme(),request.getServerName(),request.getServerPort(),file);out.println(URL.toString());32)為什么GenericServlet和HttpServlet實(shí)現(xiàn)Serializable接口?
回答:
GenericServlet和HttpServlet實(shí)現(xiàn)Serializable接口,以便servlet引擎可以在不使用servlet時“Hibernate” servlet的狀態(tài),并在需要時重新設(shè)置它的位置,或者復(fù)制servlet實(shí)例以實(shí)現(xiàn)更好的負(fù)載平衡。 我不知道當(dāng)前的servlet引擎是否或如何做到這一點(diǎn),這可能會產(chǎn)生嚴(yán)重的影響,例如在程序員不知道的情況下破壞對init()方法中獲得的對象的引用。 程序員應(yīng)意識到這一陷阱,并實(shí)現(xiàn)盡可能無狀態(tài)的Servlet,將數(shù)據(jù)存儲委派給Session對象或ServletContext。 通常,無狀態(tài)Servlet更好,因?yàn)樗鼈兊纳炜s性更好并且代碼更簡潔。
33)在覆蓋doGet(),doPost()和service()方法之間如何選擇?
回答:
doGet()和doPost()方法之間的區(qū)別在于,當(dāng)Servlet從HTTP協(xié)議請求中接收到GET或POST請求時,它們將在Servlet中通過其service()方法擴(kuò)展的HttpServlet中被調(diào)用。
GET請求是從服務(wù)器獲取資源的請求。 這是瀏覽器請求網(wǎng)頁的情況。 也可以在請求中指定參數(shù),但是總體上參數(shù)的長度受到限制。 在html中以這種方式聲明的網(wǎng)頁中的表單就是這種情況:<form method =” GET”>或<form>。
POST請求是將表單數(shù)據(jù)發(fā)布(發(fā)送)到服務(wù)器上的資源的請求。 在html中以這種方式聲明的網(wǎng)頁中的表單就是這種情況:<form method =” POST”>。 在這種情況下,參數(shù)的大小可能會更大。
GenericServlet具有一個service()方法,該方法在發(fā)出客戶端請求時被調(diào)用。 這意味著傳入請求都將調(diào)用它,并且HTTP請求將被原樣提供給servlet(您必須自己進(jìn)行解析)。
HttpServlet具有doGet()和doPost()方法,這些方法在客戶端請求為GET或POST時被調(diào)用。 這意味著請求的解析是由servlet完成的:您調(diào)用了適當(dāng)?shù)姆椒?#xff0c;并具有方便的方法來讀取請求參數(shù)。
注意: doGet()和doPost()方法(以及其他HttpServlet方法)由service()方法調(diào)用。
最后,如果您必須響應(yīng)HTTP協(xié)議客戶端(通常是瀏覽器)發(fā)出的GET或POST請求,請毫不猶豫地?cái)U(kuò)展HttpServlet并使用其便捷方法。
如果必須響應(yīng)未使用HTTP協(xié)議的客戶端發(fā)出的請求,則必須使用service()。
每種技術(shù)的優(yōu)缺點(diǎn)是什么?
回答:
Servlet擴(kuò)展了網(wǎng)站的服務(wù)器端功能。 Servlet與該服務(wù)器(或任何其他服務(wù)器)上的其他應(yīng)用程序進(jìn)行通信,并執(zhí)行“常規(guī)”靜態(tài)HTML文檔之外的任務(wù)。 Servlet可以接收一個請求,以通過EJB從一個或多個數(shù)據(jù)庫中獲取一些信息,然后將該數(shù)據(jù)轉(zhuǎn)換為靜態(tài)HTML / WML頁面,以供客戶端查看。 Even if the servlet talks to many other applications all over the world to get this information, it still looks like it happened at that website.
RMI (Remote Method Invocation) is just that – a way to invoke methods on remote machines. It is way for anapplication to talk to another remote machine and execute different methods, all the while appearing as if the action was being performed on the local machine.
Servlets (or JSP) are mainly used for any web-related activity such as online banking, online grocery stores, stock trading, etc. With servlets, you need only to know the web address and the pages displayed to you take care of calling the different servlets (or actions within a servlet) for you. Using RMI, you must bind the RMI server to an IP and port, and the client who wishes to talk to the remote server must know this IP and port, unless of course you used some kind of in-between lookup utility, which you could do with (of all things) servlets.
35) How can we use a servlet as a proxy for communications between two applets?
Answer:
One way to accomplish this is to have the applets communicate via TCP/IP sockets to the servlet. The servlet would then use a custom protocol to receive and push information between applets. However, this solution does have firewall problems if the system is to be used over and Internet verses an Intranet.
36) How can I design my servlet/JSP so that query results get displayed on several pages, like the results of a search engine? Each page should display, say, 10 records each and when the next link is clicked, I should see the next/previous 10 records and so on.
Answer:
Use a Java Bean to store the entire result of the search that you have found. The servlet will then set a pointer to the first line to be displayed in the page and the number of lines to display, and force a display of the page. The Action in the form would point back to the servlet in the JSP page which would determine whether a next or previous button has been pressed and reset the pointer to previous pointer + number of lines and redisplay the page. The JSP page would have a scriplet to display data from the Java Bean from the start pointer set to the maximum number of lines with buttons to allow previous or next pages to be selected. These buttons would be displayed based on the page number (ie if first then don't display previous button).
37) How do I deal with multi-valued parameters in a servlet?
Answer:
Instead of using getParameter() with the ServletRequest, as you would with single-valued parameters, use the getParameterValues() method. This returns a String array (or null) containing all the values of the parameter requested.
38) How can I pass data retrieved from a database by a servlet to a JSP page?
Answer:
One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:
Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:
com.foo.dbBean bean = new com.foo.dbBean();//call setters to initialize beanreq.setAttribute("dbBean", bean);url="..."; //relative url for display jsp pageServletContext sc = getServletContext();RequestDispatcher rd = sc.getRequestDispatcher(url);rd.forward(req, res);The bean can then be accessed within the JSP page via the useBean tag as:
<jsp:useBean id="dbBean" class="com.foo.dbBean" scope="request"/>...<%//iterate through the rows within dbBean and//access the values using a scriptlet%>Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of – especially if your servlets are running under a clustered or fault-tolerant architecture.
39) How can I use a servlet to generate a site using frames?
Answer:
In general, look at each frame as a unique document capable of sending its own requests and receiving its own responses. You can create a top servlet (say, FrameServlet) that upon invocation creates the frame layout you desire and sets the SRC parameters for the frame tags to be another servlet, a static page or any other legal value for SRC.
---------------------- SAMPLE ----------------------public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = new PrintWriter (response.getWriter());out.println("");out.println("Your Title");// definingthe three rows of Frames for the main page// top : frm_1// middle : frm_2// bottom : frm_3out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.close();-------------------------- END ------------------------------------------Where MenuServlet and DummyServlet provide content and behavior for the frames generated by FrameServlet.
40) What is HTTP tunneling, in the general sense?
Answer:
HTTP tunneling is a general technique whereby arbitrary data may be sent via an HTTP connection to and from CGI scripts or Java Servlets on a Web server. This is done by serializing the data to be transmitted into a stream of bytes, and sending an HTTP message with content type “application/octet-stream”.
HTTP tunneling is also referred to as Firewall tunneling.
41) How do I handle FORMs with multiple form elements (eg radio buttons) using the same name?
Answer:
For radio buttons, the HTML spec assumes that a given group of buttons will have the same NAME and different VALUEs; the browser makes sure that only one button per group name will be selected (at most). So you can just call request.getParameter(“groupname”).
<input type="radio" name="topping" value="cheese" checked>Cheese<input type="radio" name="topping" value="pepperoni">Pepperoni<input type="radio" name="topping" value="anchovies">AnchoviesIf the user selects “Pepperoni” then request.getParameter(“topping”) will return the string “pepperoni”.
For lists using the <select multiple> FORM tag, multiple values can be returned for the same parameter name. When that can happen, use request.getParameterValues(“param”) which returns a String[] you can iterate through.
It's bad form (so to speak), but you can also duplicate other element types, like
Name 1: <input type="text" name="name" value="Dick">Name 2: <input type="text" name="name" value="Jane">These also get returned in an array by request.getParameterValues().
42) How do I separate presentation (HTML) from business logic (Java) when using servlets?
Answer:
Almost anybody who has ever written a servlet can identify with this one. We all know it's bad for to embed HTML code in our java source; it's lame to have to recompile and re-deploy every time you want an HTML element to look a bit different. But what are our choices here? There are two basic options;
1. Use JSP:
Java Server Pages allows you to embed Java code or the results of a servlet into your HTML. You could, for instance, define a servlet that gives a stock quote, then use the tag in a JSP page to embed the output. But then, this brings up the same problem; without discipline, your content/presentation and program logic are again meshed. I think the ideal here is to completely separate the two.
2. Use a templating/parsing system:
Hmm…I know you're about to rant about re-inventing the wheel, but it's not that bad (see below). Plus, it really does pay to take this approach; you can have a group of programmers working on the Java code, and a group of HTML producers maintaining the interface. So now you probably want to know how to do it…so read on.
Use SSI!
Remember SSI? It hasn't gotten much attention in recent years because of embeddable scripting languages like ASP and JSP, but it still remains a viable option. To leverage it in the servlet world, I believe the best way is to use an API called SSI for Java from Areane. This API will let you emulate SSI commands from a templating system, and much more. It will let you execute any command on any system, including executing java classes! It also comes with several utility classes for creating stateful HTML form elements, tables for use with iteration, and much more. It's also open source, so it's free and you can tweak it to your heart's content! You can read the SSI for Java documentation for detailed info, but the following is an example of its use.
Here's the servlet:
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import com.areane.www.ssi.*;public class SSITemplatingServlet extends HttpServlet {private String templateFilesDirectory = "d:\\projects\\idemo\\templates\\"; //Holds path to template files/**Handles GET requests; defers every request to the POST processor*/public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException, FileNotFoundException {doPost(req, res);}/**Handles all requests. Processes the request,*saves the values, parses the file, then feeds the file to the out stream*/public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException, FileNotFoundException {HttpSession ses = req.getSession(true);Properties context = null;if((context = (Properties)ses.getValue("user.context")) == null) { //if properties doesn't already exist, create it.context = new Properties();}//Write parameters to Properties objectEnumeration paramNames = req.getParameterNames();String curName, curVal;while(paramNames.hasMoreElements()) {curName = (String)paramNames.nextElement();curVal = req.getParameter(curName);context.setProperty(curName, curVal);}//Save the values to the sessionses.putValue("user.context", context);//Parse the page and stream to the clientString templateName = req.getParameter("template"); // Get the file name of the template to useres.setContentType("text/html");SsiPage page = SsiParser.parse(this.templateFilesDirectory + templateName); //Parsing occurs herepage.write(res.getWriter(), context); //Stream to the clientpage = null; //clean up}}Now, just create a template file, pass the servlet the template file name, and have at it!
43) For an HTML FORM with multiple SUBMIT buttons, how can a servlet ond
differently for each button?
Answer:
The servlet will respond differently for each button based on the html that you have placed in the HTML page. 讓我們解釋一下。
For a submit button the HTML looks like <input type=submit name=”Left” value=”left”>. A servlet could extract the value of this submit by using the getParameter(“Left”) from the HttpRequest object. It follows then that if you have HTML within a FORM that appears as:
<input type=submit name="Direction" value="left"><input type=submit name="Direction" value="right"><input type=submit name="Direction" value="up"><input type=submit name="Direction" value="down">Then the getParameter(“Direction”) from the HttpRequest would extract the value pressed by the user, either “l(fā)eft”, “right”, “up” or “down”. A simple comparision in the servlet with the these values could occur and processing based on the submit button would be performed.
Similiarly,for submit buttons with different names on a page, each of these values could be extracted using the getParameter() call and acted on. However, in a situation where there are multiple buttons, common practice would be to use one name and multiple values to identify the button pressed.
44) What is meant by the term “business logic”?
Answer:
“Business logic” is just a fancy way of saying “code.”
More precisely, in a three-tier architecture, business logic is any code that is not specifically related to storing and retrieving data (that's “data storage code”), or to formatting data for display to the user (that's “presentation logic”). It makes sense, for many reasons, to store this business logic in separate objects; the middle tier comprises these objects. However, the divisions between the three layers are often blurry, and business logic is more of an ideal than a reality in most programs. The main point of the term is, you want somewhere to store the logic and “business rules” (another buzzword) of your application, while keeping the division between tiers clear and clean.
45) How can I explicitly unload a servlet or call the destroy method?
Answer:
In general, you can't. The Servlet API does not specify when a servlet is unloaded or how the destroy method is called. Your servlet engine (ie the implementation of the interfaces in the JSDK) might provide a way to do this, probably through its administration interface/tool (like Webshpere or JWS). Most servlet engines will also destroy and reload your servlet if they see that the class file(s) have been modified.
46) What is a servlet bean?
Answer:
A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods.
As long as you subclass GenericServlet/HttpServlet, you are automatically Serializable.
If your web server supports them, when you install the servlet in the web server, you can configure it through a property sheet-like interface.
47) Why do we need to call super.init(config) in the init method of a servlet?
Answer:
Just do as you're told and you won't get hurt!
Because if you don't, then the config object will get lost. Just extend HttpServlet, use init() (no parameters) and it'll all work ok.
From the Javadoc: init() – A convenience method which can be overridden so that there's no need to call super.init(config).
48) What is a servlet engine?
Answer:
A “servlet engine” is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is “servlet container” since that applies both to plug-in engines and to stand-alone web servers that support the Servlet API.
49) Which is the most efficient (ie processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices?
Answer:
Your question really should be broken in two.
1-What is the most efficient way of serving pages from a Java object?. There you have a clear winner in the Servlet. Althought if you are going to change the static content of the page often is going to be a pain because you'll have to change Java code. The second place in speed is for JSP pages. But, depending on your application, the difference in speed between JSP pages and raw servlets can be so small that is not worth the extra work of servlet programming.
2-What is the most efficient way of accessing a database from Java?. If JDBC is the way you want to go the I'd suggest to pick as many drivers as you can (II,III,IV or wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and usually has lousy performance. Again, go for the simplest (usually type IV driver) solution if that meets you performance needs.
For database applications, the performance bottleneck is usually the database, not the web server/engine. In this case, the use of a package that access JDBC with connection pooling at the application level used from JSP pages (with or withouth beans as middleware) is the usual choice. Of course, your applications requirements may vary.
50) How can I change the port of my Java Web Server from 8080 to something else?
Answer:
這很簡單。 JAVA WEB SERVER comes with remote Web administration tool. You can access this with a web browser.
Administration tool is located on port 9090 on your web server. To change port address for web server:
51) Can I send multiple responses for a single request?
Answer:
No. That doesn't even make sense
You can, however, send a “redirect”, which tells the user's browser to send another request, possibly to the same servlet with different parameters. Search this FAQ on “redirect” to learn more.
52) What is FORM based login and how do I use it? Also, what servlet containers support it?
Answer:
Form based login is one of the four known web based login mechanisms. For completeness I list all of them with a description of their nature:
- An authentication protocol defined within the HTTP protocol (and based on headers). It indicates the HTTP realm for which access is being negotiated and sends passwords with base64 encoding, therefore it is not very secure. (See RFC2068 for more information.)
- Like HTTP Basic Authentication, but with the password transmitted in an encrypted form. It is more secure than Basic, but less then HTTPS Authentication which uses private keys. Yet it is not currently in widespread use.
- This security mechanism provides end user authentication using HTTPS (HTTP over SSL). It performs mutual (client & server) certificate based authentication with a set of different cipher suites.
- A standard HTML form (static, Servlet/JSP or script generated) for logging in. It can be associated with protection or user domains, and is used to authenticate previously unauthenticated users.
- The major advantage is that the look and feel of the login screen can be controlled (in comparison to the HTTP browsers' built in mechanisms).
To support 1., 3., and 4. of these authentication mechanisms is a requirement of the J2EE Specification (as of v1.2, 3.4.1.3 Required Login Mechanisms). (HTTP Digest Authentication is not a requirement, but containers are encouraged to support it.)
You can also see section 3.3.11.1 of the J2EE Specs. (User Authentication, Web Client) for more detailed descriptions of the mechanisms.
Thus any Servlet container that conforms to the J2EE Platform specification should support form based login.
To be more specific, the Servlet 2.2 Specification describes/specifies the same mechanisms in 11.5 including form based login in 11.5.3.
This section (11.5.3) describes in depth the nature, the requirements and the naming conventions of form based login and I suggest to take a look at it.
Here is a sample of a conforming HTML login form:
<form method="POST" action="j_security_check"><input type="text" name="j_username"><input type="password" name="j_password"></form>Known Servlet containers that support FORM-based login are:
- iPlanet Application Server
- Tomcat (the reference implementation of the Java Servlet API)
53) How do I capture a request and dispatch the exact request (with all the parameters received) to another URL?
Answer:
As far as i know it depends on the location of the next target url.
- If the next servlet url is in the same host, then you can use the forward method.
Here is an example code about using forward:
RequestDispatcher rd = null;String targetURL = "target_servlet_name";ServletContext ctx = this.getServletContext();rd = ctx.getRequestDispatcher(targetURL);rd.forward(request, response); 54) How can the data within an HTML form be refreshed automatically whenever there is a change in the database?
Answer:
JSP is intended for dynamically generating pages. The generated pages can include wml, html, dhtml or whatever you want…
When you have a generated page, JSP has already made its work. From this moment you have a page.
If you want automatic refreshing, then this should be acomplished by the technology included in the generated page (JSP will tell only what to include in the page).
The browser can not be loaded by extern factors. The browser is the one who fetches url's since the http protocol is request-response based. If a server can reload a browser without its allow, it implies that we could be receiving pages which we haven't asked for from servers.
May you could use applets and a ServerSocket for receiving incoming signals from the server for changed data in the DB. This way you can load new information inside the applet or try to force a page reload.
[That's a nice idea — it could use the showDocument() call to reload the current page. It could also use HTTP polling instead of maintaining an expensive socket connection. -Alex]Perhaps (if possible), could be simpler using an automatic JavaScript refreshing function that force page reload after a specified time interval.
55) What is a web application (or “webapp”)?
Answer:
A web application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server. For example, a catalog application could be located at http://www.mycorp.com/catalog. All requests that start with this prefix will be routed to the ServletContext which represents the catalog application.
56) How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?
Answer:
You can use <jsp:forward page=”/relativepath/YourServlet” /> or response.sendRedirect(“http://path/YourServlet”).
Variables can be sent as:
<jsp:forward page=/relativepath/YourServlet><jsp:param name="name1" value="value1" /><jsp:param name="name2" value="value2" /></jsp:forward>You may also pass parameters to your servlet by specifying response.sendRedirect(“http://path/YourServlet?param1=val1”).
57) Can there be more than one instance of a servlet at one time ?
Answer:
It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.
58) How can I measure the file downloading time using servlets?
Answer:
59) What is inter-servlet communication?
Answer:
As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including
- Request Dispatching
- HTTP Redirect
- Servlet Chaining
- HTTP request (using sockets or the URLConnection class)
- Shared session, request, or application objects (beans)
- Direct method invocation (deprecated)
- Shared static or instance variables (deprecated)
Search the FAQ, especially topic Message Passing (including Request Dispatching) for information on each of these techniques. -Alex]
Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.
eg ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward(“NextServlet”) ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object.
eg TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet(“OtherServlet”); otherServletDetails= Test.getServletDetails();
You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls.
Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet.
60) How do I make servlet aliasing work with Apache+Tomcat?
Answer:
When you use Tomcat standalone as your web server, you can modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern:
<web-app><servlet><servlet-name>myServlet</servlet-name><servlet-class>myServlet</servlet-class></servlet><servlet-mapping><servlet-name>myServlet</servlet-name><url-pattern>/jsp-bin/*</url-pattern></servlet-mapping></web-app>This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided this trick to remedy the situation. Add the following to your tomcat-apache.conf (or to a static version of it, since tomcat re-generates the conf file every time it starts):
<LocationMatch /myApp/jsp-bin/* >SetHandler jserv-servlet</LocationMatch>This lets Apache turn over handling of the url pattern to your servlet.
61) Is there any way to determine the number of concurrent connections my servlet engine can handle?
Answer:
Depends on whether or not your servlet container uses thread pooling. If you do not use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for example, is 10. This you can see for yourself by testing a servlet with the Apache JMeter tool.
However, if your servlet container uses a thread pool, you can specify the number of concurrent connections to be accepted by the container. For Tomcat 3.1, the information on how to do so is supplied with the documentation in the TOMCAT_HOME/doc/uguide directory.
62) What is a request dispatcher and how does it work?
Answer:
A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc.
You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method.
For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp.
To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:
RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");dispatcher.forward( request, response );where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );dispatcher.forward( request, response ); 63) What is a Servlet Context?
Answer:
A Servlet Context is a grouping under which related servlets (and JSPs and other web resources) run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container .
The ServletContext object is used by an individual servlet to “call back” and obtain services from the container (such as a request dispatcher). Read the JavaDoc for javax.servlet.ServletContext for more information.
You can maintain “application global” variables by using Servlet Context Attributes .
64) Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)?
Answer:
Since the RequestDispatcher will be passing the control (request object and response object) from the current Servlet, the relative URL must be relative to the current servlet.
The originally called servlet has passed the control to the current servlet, and now current servlet is acting as controller to other resourses.
65) What is the difference between in-process and out-of-process servlet containers?
Answer:
The in-process Servlet containers are the containers which work inside the JVM of Web server, these provides good performance but poor in scalibility.
The out-of-process containers are the containers which work in the JVM outside the web server. poor in performance but better in scalibility
In the case of out-of-process containers, web server and container talks with each other by using the some standard mechanism like IPC.
In addition to these types of containers, there is 3rd type which is stand-alone servlet containers. These are an integral part of the web server.
66) How is SingleThreadModel implemented in Tomcat? In other containers? [I would assume that Tomcat uses its connection thread pool, and creates a new instance of the servlet for each connection thread, instead of sharing one instance among all threads. Is that true?]
Answer:
The question mixes together two rather independent aspects of a servlet container: “concurrency control” and “thread pooling”.
Concurrency control, such as achieved by having a servlet implement the SingleThreadModel interface, addresses the issue of thread safety. A servlet will be thread-safe or thread-unsafe regardless of whether the servlet container used a thread pool. Thread pooling merely eliminates the overhead associated with the creation and destruction of threads as a servlet container tries to respond to multiple requests received simultaneously. It is for this reason that the specification document for Servlet 2.2 API is silent on the subject of thread pooling — as it is merely an implementation detail. However, the document does indeed address the issue of thread safety and how and when to use SingleThreadModel servlets.
Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet implements the SingleThreadModel it is guaranteed “that only one request thread at time will be allowed in the service method.” It says further that “a servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances.”
Obviously, for superior performance you'd want the servlet container to create multiple instances of a SingleThreadModel type servlet should there be many requests received in quick succession. Whether or not a servlet container does that depends completely on the implementation. My experiments show that Tomcat 3.1 does indeed create multiple instances of a SingleThreadModel servlet, but only for the first batch of requests received concurrently. For subsequent batches of concurrent requests, it seems to use only one of those instances.
67) Which servlet containers have persistent session support? Specifically, does Tomcat 3.1?
Answer:
All servlet containers that implement the Servlet 2.2 API must provide for session tracking through either the use of cookies or through URL rewriting. All Tomcat servlet containers support session tracking.
68) Can I use JAAS as the authentication technology for servlets ?
Answer:
Yes, JAAS can be used as authentication technology for servlets. One important feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet.
69) How can I set a servlet to load on startup of the container, rather than on the first request?
Answer:
The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in the <servlet> section of your web.xml deployment descriptor. It is either empty (<load-on-startup/>) or contains “a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, the container is free to load it at any time in the startup sequence.”
例如,
<servlet><servlet-name>foo</servlet-name><servlet-class>com.foo.servlets.Foo</servlet-class><load-on-startup>5</load-on-startup></servlet>Some servlet containers also have their own techniques for configuring this; please submit feedback with information on these.
70) Is it possible to write a servlet that acts as a FTP server?
Answer:
是。 It would spawn a thread that opens a ServerSocket, then listens for incoming connections and speaks the FTP protocol.
71) Is there a way to disable a user's ability to double-click a submit image/button (and therefore submitting duplicate data — multiple submits)? Is there a way to do this with Javascript?
Answer:
Give the submit image (or button) an onClick() handler. Have the handler check if a flag is set and if not set the flag and submit the form and then clear the form.
72) What are the main differences between Servlets and ISAPI?
Answer:
The first difference is obviously that Servlets is the technology from Sun Microsystems and ISAPI is from Microsoft.
Other Differences are:
73) Can I associate a servlet with a particular mime-type, so if the client requests a file of that type, my servlet will be executed?
Answer:
In web.xml you can use a mime-mapping to map the type with a certain extension and then map the servlet to that extension.
例如
<mime-mapping><extension>zzz</extension><mime-type>text/plain</mime-type></mime-mapping><servlet-mapping><url>*.zzz</url><servlet-name>MyServlet</servlet-name></servlet-mapping>So, when a file for type zzz is requested, the servlet gets called.
74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()?
Answer:
When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
If you don't need to preserve the request/response objects, you can use either.
75) How do I access the value of a cookie using JavaScript?
Answer:
You can manipulate cookies in JavaScript with the document.cookie property. You can set a cookie by assigning this property, and retrieve one by reading its current value.
The following statement, for example, sets a new cookie with a minimum number of attributes:
document.cookie = "cookieName=cookieValue";And the following statement displays the property's value:
alert(document.cookie);The value of document.cookie is a string containing a list of all cookies that are associated with a web page. It consists, that is, of name=value pairs for each cookie that matches the current domain, path, and date. The value of the document.cookie property, for instance, might be the following string:
cookieName1=cookieValue1; cookieName2=cookieValue2; 76) How do I write to a log file using JSP under Tomcat? Can I make use of the log() method for this?
Answer:
Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets. These messages are stored in the server's log directory in a file called servlet.log.
77) How can I use a servlet to print a file on a printer attached to the client?
Answer:
The security in a browser is designed to restrict you from automating things like this. However, you can use JavaScript in the HTML your servlet returns to print a frame. The browser will still confirm the print job with the user, so you can't completely automate this. Also, you'll be printing whatever the browser is displaying (it will not reliably print plug-ins or applets), so normally you are restricted to HTML and images.
[The JavaScript source code for doing this is: <input type="button" onClick="window.print(0)" value="Print This Page"> 78) How do you do servlet aliasing with Apache and Tomcat?
Answer:
Servlet aliasing is a two part process with Apache and Tomcat. First, you must map the request in Apache to Tomcat with the ApJServMount directive, eg,
ApJServMount/myservlet/ROOT
Second, you must map that url pattern to a servlet name and then to a servlet class in your web.xml configuration file. Here is a sample exerpt:
<servlet><servlet-name>myservlet</servlet-name><servlet-class>com.mypackage.MyServlet</servlet-class></servlet><servlet-mapping><servlet-name>myservlet</servlet-name><url-pattern>/myservlet</url-pattern></servlet-mapping> 79) I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out?
Answer:
If the servlet engine does the time-out, following code should help you:
//assume you have a HttpServletRequest requestif(request.getSession(false)==null) {//no valid session (timeouted=invalid)//code to redirect to login page} 80) Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension?
Answer:
yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:
<servlet-mapping><servlet-name>jsp</servlet-name><url>*.html</url></servlet-mapping>And comment out the following block
<mime-mapping><extension>html</extension><mime-type>text/html</mime-type></mime-mapping> 81) What is the difference between request attributes, session attributes, and ServletContext attributes?
Answer:
A ServletContext attribute is an object bound into a context through ServletContext.setAttribute() method and which is available to ALL servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications.
Session attributes are bound to a session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the session implementing the HttpSessionBindingListener interface.
Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keep dispatched from servlet to servlet. They're used more as comunication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters…) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy.
Thus we can say that context attributes are meant for infra-structure such as shared connection pools, session attributes to contextual information such as user identification, and request attributes are meant to specific request info such as query results.
82) Are singleton/static objects shared between servlet contexts?
[Question continues: For example if I have two contexts on a single web server, and each context uses a login servlet and the login servlet connects to a DB. The DB connection is managed by a singleton object. Do both contexts have their own instance of the DB singleton or does one instance get shared between the two?] Answer:
It depends on from where the class is loaded.
The classes loaded from context's WEB-INF directory are not shared by other contexts, whereas classes loaded from CLASSPATH are shared. So if you have exactly the same DBConnection class in WEB-INF/classes directory of two different contexts, each context gets its own copy of the singleton (static) object.
83) When building web applications, what are some areas where synchronization problems arrise?
Answer:
In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request.
Typical examples include:
- Connections to external servers, especially if you have any sort of pooling.
- Anything which you include in a HttpSession. (Your user could open many browser windows and make many simultaneous requests within the one session.)
- Log destinations, if you do your own logging from your servlets.
84) What is the difference between apache webserver, java webserver and tomcat server?
Answer:
Apache is an HTTP server written in C that can be compiled and run on many platforms.
Java WebServer is an HTTP server from Sun written in Java that also supports Servlets and JSP.
Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a “plug-in” to native-code HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server).
85) How can you embed a JavaScript within servlets / JSP pages?
Answer:
You don't have to do anything special to include JavaScript in servlets or JSP pages. Just have the servlet/JSP page generate the necessary JavaScript code, just like you would include it in a raw HTML page.
The key thing to remember is it won't run in the server. It will run back on the client when the browser loads the generate HTML, with the included JavaScript.
86) How can I make a POST request through response.sendRedirect() or response.setStatus() and response.setHeader() methods?
Answer:
你不能 It's a fundamental limitation of the HTTP protocol. You'll have to figure out some other way to pass the data, such as
- Use GET instead
- Make the POST from your servlet, not from the client
- Store data in cookies instead of passing it via GET/POST
87) How do I pass a request object of one servlet as a request object to another servlet?
Answer:
Use a Request Dispatcher.
88) I call a servlet as the action in a form, from a jsp. How can I redirect the response from the servlet, back to the JSP? (RequestDispatcher.forward will not help in this case, as I do not know which resource has made the request. request.getRequestURI will return the uri as contained in the action tag of the form, which is not what is needed.)
Answer:
You'll have to pass the JSP's URI in to the servlet, and have the servlet call sendRedirect to go back to the JSP. 例如:
<FORM ACTION="/foo/myservlet"><INPUT TYPE="HIDDEN" NAME="redirect" VALUE="/foo/thisjsp.jsp">Shoe size: <INPUT NAME="shoesize"><INPUT TYPE="SUBMIT"></FORM>Then in the servlet…
response.sendRedirect(request.getParameter("redirect")); 89) What is the ServletConfig object, and why is it useful?
Answer:
The ServletConfig object is an interface. It contains the methods
- getInitParameter
- getInitParameterNames
- getServletContext
- getServletName
You can use the methods to determine the Servlet's initialization parameters, the name of the servlets instance, and a reference to the Servlet Context the servlet is running in.
getServletContext is the most valuable method, as it allows you to share information accross an application (context).
90) I have a global variable in a servlet class. What will happen to this global variable if two requests hit on the same time?
Answer:
What will happen is an unforeseeable event.
The best way to establish a default occurrence (the servlet handles a request at a time) is to synchronize the access to the global variable or alternatively to create a servlet that implements the SingleThreadModel interface.
91) Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2?
Answer:
You'll have to create a (new) similar cookie on server 2.
Have a ReadCookieServlet running on server1 that
- Reads the cookie, using request.getCookies()
- Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect() .
Have a WriteCookieServlet running on server2 that
- Reads the cookie name, value and expiration date request parameters, using request.getParameter() .
- Creates a similar cookie, using response.addCookie() .
92) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?
Answer:
There are three ways I can think of off the top of my head:
93) How can I write an “error page” — that is, a servlet or JSP to report errors of other servlets?
Answer:
The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP) for different kinds of HTTP errors or ServletExceptions. You can specify this in deployment descriptor of the web application as:
<error-page><exception-type>FooException</exception-type><location>/error.jsp</location></error-page>where FooException is a subclass of ServletException.
The web container invokes this servlet in case of errors, and you can access the following information from the request object of error servlet/JSP: error code, exception type, and a message.
94) What is the difference between ServletContext and ServletConfig?
Answer:
A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.
This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said “servlet instance”, not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations.
This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.
95) Under what circumstances will a servlet be reloaded?
Answer:
That depends on the Servlet container.
Most of the Servlet containers reload the servlet only it detects the code change in the Servlet, not in the referenced classes.
In Tomcat's server.xml deployment descriptor, if you have mentioned
<Context path="/myApp"docBase="D:/myApp/webDev"crossContext="true"debug="0"reloadable="true"trusted="false" ></Context>The reloadable = true makes the magic. Every time the Servlet container detects that the Servlet code is changed, it will call the destroy on the currently loaded Servlet and reload the new code.
But if the class that is referenced by the Servlet changes, then the Servlet will not get loaded. You will have to change the timestamp of the servlet or stop-start the server to have the new class in the container memory.
96) What is a Servlet Filter?
Answer:
A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client.
97) I am using the RequestDispatcher's forward() method to redirect to a JSP. The problem is that the jsp's url is now relative to the servlet's url and all my url's in the jsp such as <img src=”pic.gif”> will be corrupt. How do I solve this problem?
Answer:
You can use absolute urls like:
<BODY><% String base = request.getContextPath(); %><IMG src="<%=base%>/img/pic.gif"></BODY>or write out a BASE tag like:
<% String base = request.getContextPath(); %><HEAD><BASE HREF="<%=base%>"></HEAD><BODY><IMG src="img/pic.gif"></BODY>That should take care of the problem.
98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet?
Answer:
To solve your problem, you can either send a “Redirect” back to the client or use a RequestDispatcher and forward your request to another page:
A redirection is made using the HttpServletResponse object:
if(condition) {response.sendRedirect("page1.html");} else {response.sendRedirect("page2.html");}A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it.
if(condition) {this.getServletContext().getRequestDispatcher("page1.html").forward();} else {this.getServletContext().getRequestDispatcher("page2.html").forward();}Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer.
If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server.
99) What is the difference between static variables and instance variables in a servlet?
Answer:
According to the Java Language definition, a static variable is shared among all instances of a class, where a non-static variable — also called an instance variable — is specific to a single instance of that class.
According to the Servlet specification, a servlet that does not declare SingleThreadModel usually has one and only one instance, shared among all concurrent requests hitting that servlet.
That means that, in servlets (and other multithreaded applications), an instance variable behaves very much like a static variable, since it is shared among all threads. You have to be very careful about synchronizing access to shared data.
The big difference between instance variables and static variables comes when you have configured your servlet engine to instantiate two instances of the same servlet class, but with different init parameters. In this case, there will be two instances of the same servlet class, which means two sets of instance variables, but only one set of static variables.
Remember that you can store data in lots of different places in a servlet. 以機(jī)智:
- Local variables – for loop iterators, result sets, and so forth
- Request attributes – for data that must be passed to other servlets invoked with the RequestDispatcher
- Session attributes – persists for all future requests from the current user only
- Instance variables – for data that persists for the life of the servlet, shared with all concurrent users
- Static variables – for data that persists for the life of the application, shared with all concurrent users — including any other servlet instances that were instantiated with different init parameters
- Context attributes – for data that must persist for the life of the application, and be shared with all other servlets
100) How can I share data between two different web applications?
Answer:
Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications, you may wanna consider using EJBs.
翻譯自: https://www.javacodegeeks.com/2013/09/top-100-java-servlet-questions.html
java servlet
總結(jié)
以上是生活随笔為你收集整理的java servlet_Java Servlet的前100个问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 燕秀模具快捷键(燕秀模具自动出图好不好用
- 下一篇: 怎样在电脑看3d电影(如何在电脑看3d电