Java Servlet的前100个问题
1)是“ servlets”目錄還是“ servlet”目錄?
回答:
對于Java Web Server:
- 在文件系統上,它是“ servlet”
c:\ JavaWebServer1.1 \ servlets \ DateServlet.class
- 在URL路徑中,它是“ servlet”: http : //www.stinky.com/servlet/DateServlet
2)如何從同一個Servlet支持GET和POST協議?
回答:
簡單的方法是,僅支持POST,然后讓您的doGet方法調用您的doPost方法:
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{doPost(req, res);}3)如何確保我的servlet是線程安全的?
回答:
這實際上是一個非常復雜的問題。 一些準則:
(請注意,如果您使用新名稱(例如,新的init參數)注冊servlet,則服務器還將分配新的實例。)
另請參見什么是啟用線程安全的servlet和JSP的更好方法? SingleThreadModel接口還是同步?
4)URL編碼,URL重寫,HTML轉義和實體編碼之間有什么區別?
回答:
URL編碼
是將用戶輸入轉換為CGI表單的過程,因此適合于跨網絡旅行-基本上是刪除空格和標點符號,并以轉義符代替。 URL解碼是相反的過程。 要執行這些操作,請調用java.net.URLEncoder.encode()和java.net.URLDecoder.decode()(后者已(最終!)添加到了JDK 1.2(又名Java 2)中)。
例:
更改“我們是第一!” 變成“我們%27re +%231%21”
URL重寫
是一種在兩次頁面點擊之間將狀態信息保存在用戶瀏覽器上的技術。 有點像cookie,只是信息被存儲在URL中,作為附加參數。 HttpSession API是Servlet API的一部分,有時在cookie不可用時會使用URL重寫。
例:
將<A HREF=”nextpage.html”>更改為
<A HREF=”nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE”>(或實際語法是什么;我忘記了)(不幸的是,Servlet API中用于為會話管理進行URL重寫的方法稱為encodeURL()。嘆…)
Apache Web服務器還有一個名為URL Rewriting的功能。 它由mod_rewrite模塊啟用。 它會在進入服務器的過程中重寫URL,從而使您可以執行以下操作,例如將斜杠自動添加到目錄名,或將舊文件名映射到新文件名。 這與servlet無關。
5)如何將文件上傳到我的servlet或JSP?
回答:
在客戶端,客戶端的瀏覽器必須支持基于表單的上傳。 大多數現代瀏覽器都可以,但不能保證。 例如,
<FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'><INPUT TYPE='file' NAME='mptest'><INPUT TYPE='submit' VALUE='upload'></FORM>輸入類型“文件”可被輸入。 會在瀏覽器上彈出一個用于文件選擇框的按鈕,并帶有一個文本字段,該文本字段將在選定文件后顯示文件名。 當請求的POST正文包含要解析的文件數據時,servlet可以使用GET方法參數來決定如何處理上傳。
當用戶單擊“上傳”按鈕時,客戶端瀏覽器將找到本地文件并使用HTTP POST發送該文件,該文件使用MIME類型的multipart / form-data進行編碼。 當它到達您的servlet時,您的servlet必須處理POST數據以便提取編碼的文件。 您可以在RFC 1867中了解有關此格式的所有信息。
不幸的是,Servlet API中沒有方法可以做到這一點。 幸運的是,有許多可用的庫。 其中一些假設您將把文件寫入磁盤。 其他人將數據作為InputStream返回。
- Jason Hunter的MultipartRequest (可從http://www.servlets.com/獲得 )
- Apache Jakarta Commons Upload (軟件包org.apache.commons.upload)“使向Servlet和Web應用程序添加強大,高性能的文件上傳功能變得容易”
- 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提供了一組免費的JSP,用于執行文件上傳和下載。
- JavaZoom的UploadBean聲稱可以為您處理大部分的上傳麻煩,包括寫入磁盤或內存。
- dotJ中有一個上傳標簽
將表單數據流處理為上載文件后,您可以根據需要將其寫入磁盤,將其寫入數據庫或作為InputStream處理。 請參閱如何從servlet內部訪問或在當前目錄中創建文件或文件夾? Servlets:Files主題中的其他問題以及有關從Servlet寫入文件的信息。
請注意 ,您不能直接從Servlet訪問客戶端系統上的文件; 那將是一個巨大的安全漏洞。 您必須征求用戶的許可,當前基于表單的上傳是唯一的方式。
6)servlet如何與JSP頁面通信?
回答:
以下代碼段顯示了Servlet如何實例化bean并使用瀏覽器發布的FORM數據對其進行初始化。 然后將bean放入請求中,然后通過請求分派器將調用轉發到JSP頁面Bean1.jsp,以進行下游處理。
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操作從默認請求范圍提取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技術易于使用,并且在低容量站點上效果很好,但是它的伸縮性不好。 如果您希望用戶將來會增加,那么最好對共享數據實施顯式同步。 但是,關鍵是要有效地最小化同步的代碼量,以便最大程度地利用多線程。
另外,請注意,從服務器的角度來看,SingleThreadModel占用大量資源。 但是,最嚴重的問題是并發請求數耗盡了servlet實例池。 在這種情況下,所有未服務的請求都將排隊等待,直到有空閑的東西為止–這會導致性能下降。 由于使用情況不確定,因此即使您確實增加了內存并增加了實例池的大小,也可能無濟于事。
8)Servlet可以在多個Servlet調用之間維護JTA UserTransaction對象嗎?
回答:
不能。JTA事務必須在一次調用(對service()方法)中開始和完成。 請注意,此問題并未解決維護和操作JDBC連接(包括連接的事務處理)的servlet。
與Perl腳本相比如何?
回答:
JSP頁面的性能非常接近servlet。 但是,當第一次訪問JSP頁面時,用戶可能會遇到明顯的延遲。 這是因為JSP頁面經歷了“翻譯階段”,在此階段,JSP頁面將其轉換為servlet。 一旦該Servlet被動態編譯并加載到內存中,它將遵循Servlet生命周期進行請求處理。 在此,JSP引擎在加載servlet時會自動調用jspInit()方法,然后是_jspService()方法,該方法負責處理請求并回復客戶端。 請注意,此Servlet的生存期是不確定的–出于資源相關的原因,JSP引擎可隨時將其從內存中刪除。 發生這種情況時,JSP引擎會自動調用jspDestroy()方法,從而允許Servlet釋放任何先前分配的資源。
只要Servlet緩存在內存中,隨后對JSP頁面的客戶端請求就不會重復轉換階段,而是由Servlet的service()方法以并發方式直接處理(即,service()方法處理每個客戶請求同時在單獨的線程中)。
最近有一些研究將Servlet的性能與在“真實”環境中運行的Perl腳本進行了對比。 結果對Servlet有利,尤其是當它們在集群環境中運行時。
10)如何從另一個servlet調用一個servlet?
回答:
[簡短答案:有幾種方法可以做到這一點,包括
- 使用RequestDispatcher
- 使用URLConnection或HTTPClient
- 發送重定向
- 調用getServletContext()。getServlet(name)(不建議使用,在2.1+版本中不起作用)
–亞歷克斯]
這取決于您所說的“通話”的含義,您要做什么以及為什么要這么做。
如果最終的結果是調用方法,那么最簡單的機制就是將servlet像任何java對象一樣對待,創建一個實例并調用該方法。
如果您的想法是從另一個Servlet的服務方法中調用服務方法,即轉發請求,則可以使用RequestDispatcher對象。
但是,如果要訪問由servlet引擎加載到內存中的servlet實例,則必須知道servlet的別名。 (如何定義它取決于引擎。)例如,要在JSDK中調用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服務器,應用程序服務器等)
回答:
與處理和處理用戶請求有關的服務器分為幾種基本類型,每種基本類型都有其要解決的一個或多個任務。 這種靈活性為開發人員提供了在如何創建和部署應用程序方面的強大功能,但也導致對服務器能夠或應該執行特定任務的困惑。
從基本級別開始,用戶通常是通過Web瀏覽器向系統提交請求。 (為清楚起見,我們暫時忽略了所有其他類型的客戶端(RMI,CORBA,COM / DCOM,自定義等)。)Web請求必須由Web服務器接收(否則稱為Web服務器)。 HTTP Server )。 該Web服務器必須處理標準的HTTP請求和響應,通常將HTML返回給調用用戶。 在服務器環境中執行的代碼可能是CGI驅動,Servlet,ASP或某些其他服務器端編程語言,但是最終結果是Web服務器將HTML返回給用戶。
Web服務器可能需要響應用戶請求執行應用程序。 它可能正在生成新聞列表,或處理向訪客留言簿的表單提交。 如果服務器應用程序是用Java Servlet編寫的,則它將需要一個執行位置,該位置通常稱為Servlet Engine 。 取決于Web服務器,此引擎可以是內部,外部或完全不同的產品。 該引擎一直在運行,這與傳統的CGI環境不同,在傳統的CGI環境中,每次向服務器發出請求時都會啟動CGI腳本。 這種持久性提供了Servlet連接和線程池,以及維護每個HTTP請求之間狀態的簡便方法。 JSP頁面通常與servlet引擎綁定在一起,并且將在與servlet相同的空間/應用程序中執行。
有許多產品以不同的方式處理Web服務和Servlet引擎。 Netscape / iPlanet Enterprise Server將Servlet引擎直接構建到Web服務器中,并在同一進程空間中運行。 Apache要求Servlet引擎在外部進程中運行,并且將通過TCP / IP套接字與該引擎進行通信。 其他服務器(例如MS IIS)并不正式支持servlet,并且需要附加產品才能添加該功能。
當您繼續使用Enterprise JavaBeans(以及其他J2EE組件,例如JMS和CORBA)時,您將進入應用程序服務器空間。 應用程序服務器是任何提供與企業計算相關的附加功能的服務器,例如,負載平衡,數據庫訪問類,事務處理,消息傳遞等。
EJB Application Server提供了一個EJB容器,Bean將在該容器中執行該環境,并且該容器將根據需要管理事務,線程池和其他問題。 這些應用程序服務器通常是獨立產品,開發人員可以通過遠程對象訪問API將其servlet / JSP頁面綁定到EJB組件。 根據應用服務器的不同,程序員可以使用CORBA或RMI與他們的bean進行通信,但是基線標準是根據需要使用JNDI來定位和創建EJB引用。
現在,使這個問題困惑的一件事是,許多應用程序服務器提供程序在其產品中都包含了部分或全部這些組件。 如果查看WebLogic(http://www.beasys.com/),您會發現WebLogic包含Web服務器,servlet引擎,JSP處理器,JMS工具以及EJB容器。 從理論上講,此類產品可用于處理站點開發的所有方面。 實際上,您最有可能使用這種類型的產品來管理/服務EJB實例,而專用的Web服務器則處理特定的HTTP請求。
12)我應該重寫service()方法嗎?
回答:
不。它提供了很多您只需要自己做的內務處理。 如果無論請求是POST還是GET都需要執行某些操作,請創建一個輔助方法,并在doPost()和doGet()的開頭調用該方法。
13)我的應用程序如何知道刪除HttpSession的時間(超時)?
回答:
定義一個類,例如SessionTimeoutNotifier,該類實現javax.servlet.http.HttpSessionBindingListener。 創建一個SessionTimeoutNotifier對象,并將其添加到用戶會話中。 刪除會話后,Servlet引擎將調用SessionTimeoutNotifier.valueUnbound()。 您可以實現valueUnbound()來做任何您想做的事情。
14)當我們可以對servlet執行相同的操作時,為什么要使用JSP?
[原始問題:當已經有servlet技術可用于提供動態內容時,為什么我應該使用JSP?]
回答:
盡管JSP可以很好地提供動態Web內容并將內容與表示分離,但是有些人可能仍想知道為什么應將servlet拋給JSP。 servlet的實用程序不成問題。 它們非常適合服務器端處理,并且由于其龐大的安裝基礎,因此可以保留。 實際上,從架構上來說,您可以將JSP視為Servlet的高級抽象,它是Servlet 2.1 API的擴展而實現的。 不過,您不應該隨意使用servlet。 它們可能并不適合所有人。 例如,盡管頁面設計人員可以使用常規HTML或XML工具輕松編寫JSP頁面,但servlet更適合于后端開發人員,因為它們通常使用IDE編寫-這種過程通常需要更高水平的編程專業知識。
部署servlet時,甚至開發人員也必須小心,并確保表示和內容之間沒有緊密的聯系。 通常,您可以通過在混合中添加第三方HTML包裝程序包(例如htmlKona)來實現此目的。 但是,即使采用這種方法,盡管可以通過簡單的屏幕更改提供一定的靈活性,但仍然不能阻止您更改演示格式本身。 例如,如果您的演示文稿從HTML更改為DHTML,則仍需要確保包裝程序包與新格式兼容。 在最壞的情況下,如果沒有包裝程序包,則最終可能會在動態內容中對演示文稿進行硬編碼。 那么,解決方案是什么? 一種方法是同時使用JSP和Servlet技術來構建應用程序系統。
15)如何使用HTTP協議在applet和servlet之間來回發送信息和數據?
回答:
使用標準的java.net.URL類,或使用java.net.Socket“自己動手”。 請參閱HTTP規范
有關詳細信息,請訪問W3C。
注意: Servlet無法啟動此連接! 如果servlet需要異步將消息發送到applet,則必須使用java.net.Socket(在applet端)以及java.net.ServerSocket和Threads(在服務器端)打開持久套接字。
16)我可以獲取當前servlet在文件系統上的路徑(不是URL)嗎?
回答:
嘗試使用:
request.getRealPath(request.getServletPath())一個示例可能是:
out.println(request.getRealPath(request.getServletPath()));17)如何以菊花鏈方式將servlet鏈接在一起,以使一個servlet的輸出成為下一個servlet的輸入?
回答:
有兩種常見的方法將一個servlet的輸出鏈接到另一個servlet:
要將servlet鏈接在一起,必須指定servlet的順序列表,并將其與別名關聯。 當對該別名發出請求時,將調用列表中的第一個servlet,處理其任務,并將輸出作為請求對象發送到列表中的下一個servlet。 輸出可以再次發送到另一個servlet。
要實現此方法,您需要配置servlet引擎(JRun,JavaWeb服務器,JServ…)。
例如,要為Servlet鏈配置JRun,請選擇JSE服務(JRun Servlet引擎)以訪問“ JSE服務配置”面板。 您只需定義一個新的映射規則,即可在其中定義鏈接servlet。
假設使用/ servlets / chainServlet表示虛擬路徑,并用逗號分隔servlet列表,如srvA,srvB。
因此,當您調用諸如http:// localhost / servlets / chainServlet之類的請求時,將首先在內部調用servlet srvA,并將其結果傳遞到servlet srvB中。
srvA servlet代碼應如下所示:
public class srvA extends HttpServlet {...public void doGet (...) {PrintWriter out =res.getWriter();rest.setContentType("text/html");...out.println("Hello Chaining servlet");}}servlet srvB所要做的就是打開請求對象的輸入流,并將數據讀入BufferedReader對象,例如:
BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) );String data = b.readLine();b.close();之后,您可以使用數據格式化輸出。
它也應該可以與Java Web Server或Jserv一起使用。 只需查看他們的文檔即可定義別名。 希望對您有所幫助。
18)為什么servlet中沒有構造函數?
回答:
就其具有充當構造函數的init()方法而言,Servlet就像小應用程序一樣。 由于servlet環境負責實例化servlet,因此不需要顯式的構造函數。 您需要運行的任何初始化代碼都應放在init()方法中,因為它是在Servlet容器首次加載Servlet時被調用的。
19)將JDBC與Servlet一起使用時,如何處理多個并發數據庫請求/更新?
回答:
每當修改數據時,所有的dbms都提供鎖定功能。 可以有兩種情況:
JDBC文檔中解決了此問題。 查找“交易”和“自動提交”。 可能會造成混亂。
20)GenericServlet和HttpServlet有什么區別?
回答:
GenericServlet適用于可能不使用HTTP的Servlet,例如FTP Servlet。 當然,事實證明,沒有像FTP servlet這樣的東西,但是他們在設計規范時正試圖為將來的增長做計劃。 也許有一天會有另一個子類,但是現在,始終使用HttpServlet。
21)如何在Servlet和JSP之間共享會話對象?
回答:
Servlet和JSP頁面之間的共享會話很簡單。 JSP通過創建會話對象并使其變得可用來使其變得容易一些。 在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程序擴展Web服務器以執行以前由CGI腳本或專有服務器擴展框架處理的任務的一種方式。
23)是否有什么方法可以在不重新啟動服務器的情況下從Web服務器內存中卸載servlet?
回答:
沒有標準的方法/機制可以從內存中卸載servlet。 某些服務器(例如JWS)提供了從其管理模塊加載和卸載servlet的方法。 其他人(例如Tomcat)要求您僅替換WAR文件。
24)JavaBean和Servlet有什么區別?
回答:
JavaBeans是創建可重用的軟件組件或bean遵循的一組規則。 這包含屬性和事件。 最后,您有了一個可由程序(例如IDE)檢查的組件,以允許JavaBean組件的用戶對其進行配置并在其Java程序中運行。
Servlet是在Servlet引擎中運行的Java類,實現了特定的接口:Servlet,強制您實現某些方法(service())。 Servlet是運行該Servlet的Web服務器的擴展,僅當用戶請求從網頁向Servlet的GET或POST調用時才通知您。
因此,除了Java之外,兩者都沒有共同點。
25)我們可以在一個會話對象中存儲多少數據?
回答:
由于會話保留在服務器端,因此可以在其中存儲任何數量的數據。
唯一的限制是sessionId長度,該長度不得超過?4000字節-HTTP標頭長度限制為4Kb暗示了此限制,因為sessionId可能存儲在cookie中或以URL編碼(使用“ URL rewriting ”)和cookie規范表示Cookie和HTTP請求(例如GET /document.html\n)的大小不能超過4kb。
26)doGet和doPost方法之間有什么區別?
回答:
調用doGet以響應HTTP GET請求。 當用戶單擊鏈接或在瀏覽器的地址欄中輸入URL時,就會發生這種情況。 某些HTML FORM(在FORM標記中指定了METHOD =“ GET”HTML FORM)也會發生這種情況。
調用doPost以響應HTTP POST請求。 這在某些HTML FORM(在FORM標記中指定了METHOD =“ POST”HTML FORM)中會發生。
HttpServlet基類中的服務的默認(超類)實現調用這兩種方法。 您應該覆蓋一個或兩個來執行servlet的動作。 您可能不應該重寫service()。
27)encodeRedirectUrl和encodeURL有什么區別?
回答:
encodeURL和encodeRedirectURL是HttpResponse對象的方法。 如有必要,兩者都重寫原始URL以包括會話數據。 (如果啟用了cookie,則兩個都不操作。)
encodeURL用于HTML頁面內的普通鏈接。
encodeRedirectURL用于傳遞給response.sendRedirect()的鏈接。 它對語法的要求略有不同,因此不適合在這里使用。
28)我可以在servlet中使用System.exit()嗎?
回答:
加油! 不不不不不…
充其量,您將獲得一個安全例外。 最糟糕的是,您將使servlet引擎或整個Web服務器退出。 你真的不想那樣吧?
我需要在Connection或Statement對象上進行同步嗎?
回答:
不用了 如果您的JDBC驅動程序支持多個連接,那么即使其他請求/線程也正在訪問同一連接上的其他語句,各種createStatement方法也會為您提供一個線程安全,可重入,獨立的語句,該語句應該可以正常工作。
當然,雙手合十不會傷人……許多早期的JDBC驅動程序并沒有重入。 現代版本的JDBC驅動程序應該可以正常運行,但是永遠不能保證。
使用連接池可以避免整個問題,并且可以提高性能。
30)如何確定正在使用的servlet或JSP引擎的名稱和版本號?
回答:
在Servlet內,您可以按以下方式調用ServletContext.getServerInfo()方法:
String thisServer= getServletConfig().getServletContext().getServerInfo();如果使用的是JSP,則可以使用以下表達式:
<%= application.getServerInfo() %>31)如何在運行時獲取servlet / JSP頁面的絕對URL?
回答:
您可以獲取所有必要信息,以便從請求對象確定URL。 要從方案,服務器名稱,端口,URI和查詢字符串重構絕對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實現Serializable接口?
回答:
GenericServlet和HttpServlet實現Serializable接口,以便servlet引擎可以在不使用servlet時“休眠” servlet的狀態,并在需要時重新設置它的位置,或者復制servlet實例以實現更好的負載平衡。 我不知道當前的servlet引擎是否或如何做到這一點,這可能會產生嚴重的影響,例如在程序員不知道的情況下破壞對init()方法中獲得的對象的引用。 程序員應該意識到這一陷阱,并實現盡可能無狀態的Servlet,將數據存儲委托給Session對象或ServletContext。 通常,無狀態Servlet更好,因為它們的伸縮性更好并且代碼更簡潔。
33)在覆蓋doGet(),doPost()和service()方法之間如何選擇?
回答:
doGet()和doPost()方法之間的區別在于,當Servlet從HTTP協議請求中接收到GET或POST請求時,它們會在servlet中通過其service()方法在HttpServlet中調用。
GET請求是從服務器獲取資源的請求。 這是瀏覽器請求網頁的情況。 也可以在請求中指定參數,但是總體上參數的長度受到限制。 在html中這樣聲明的網頁中的表單就是這種情況:<form method =” GET”>或<form>。
POST請求是將表單數據發布(發送)到服務器上的資源的請求。 在html中這樣聲明的網頁中的表單就是這種情況:<form method =” POST”>。 在這種情況下,參數的大小可能會更大。
GenericServlet具有一個service()方法,該方法在發出客戶端請求時被調用。 這意味著傳入請求都將調用它,并且HTTP請求將被照原樣提供給Servlet(您必須自己進行解析)。
HttpServlet具有doGet()和doPost()方法,這些方法在客戶端請求為GET或POST時被調用。 這意味著請求的解析是由servlet完成的:您調用了適當的方法,并具有方便的方法來讀取請求參數。
注意: doGet()和doPost()方法(以及其他HttpServlet方法)由service()方法調用。
最后,如果您必須響應HTTP協議客戶端(通常是瀏覽器)發出的GET或POST請求,請毫不猶豫地擴展HttpServlet并使用其便捷方法。
如果必須響應未使用HTTP協議的客戶端發出的請求,則必須使用service()。
每種技術的優缺點是什么?
回答:
Servlet擴展了網站的服務器端功能。 Servlet與該服務器(或任何其他服務器)上的其他應用程序進行通信,并執行“常規”靜態HTML文檔之外的任務。 Servlet可以接收一個請求,以通過EJB從一個或多個數據庫中獲取一些信息,然后將該數據轉換為靜態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.
這是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. Let's explain.
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 “left”, “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:
You can't. 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. To wit:
- 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的前100个问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux本地ip怎么查看(linux
- 下一篇: 单元测试Java Hadoop作业