使内嵌式jetty服务器支持jsp
1.jetty是什么
jetty是一個輕量級的web服務器,類似tomcat,但用起來比tomcat靈活,尤其是支持內嵌式使用。所謂內嵌式即以java語句的形式啟動jetty,這樣我們可以無需部署和啟動web容器就能達到同樣的效果。這對于簡單的基于http協議的應用以及調試程序就方便的多了。
2.一個簡單的jetty服務器
簡單到僅需類似以下幾條語句:
public?class?JettySample?{public?static?void?main(String[]?args)throws?Exception{Server?server=new?Server(8087);Context?context=new?Context(server,"/");ResourceHandler?resource_handler=new?ResourceHandler();resource_handler.setWelcomeFiles(new?String[]{"index.html"});resource_handler.setResourceBase(".");context.setHandler(resource_handler);server.setStopAtShutdown(true);server.start();} }當選擇Run As Java Application來運行時,即啟動了一個端口號為8087的web服務器。
當然上面的例子只能解析html文件,如需解析servlet和jsp還需要其他一些工作。servlet還好說,調試jsp費了點勁,下面是記錄過程。
3.試了好多種方法,看了不少的帖子,最終我發現解析jsp和解析servlet方法是不同的,不能僅通過增加幾條語句(如context.addServlet(new?ServletHolder(new?HelloServlet()),?"/hello");)就能完成,而必須要建立一個所謂的web應用,所以格式上就和上面的代碼略有差別。
public?static?void?main(String[]?args)?throws?Exception{Server?server?=?new?Server();Connector?connector?=?new?SelectChannelConnector();connector.setPort(8080);server.setConnectors(new?Connector[]?{?connector?});?WebAppContext?webAppContext?=?new?WebAppContext("WebContent","/");webAppContext.setDescriptor("WebContent/WEB-INF/web.xml");webAppContext.setResourceBase("WebContent");webAppContext.setDisplayName("jetty");webAppContext.setClassLoader(Thread.currentThread().getContextClassLoader());webAppContext.setConfigurationDiscovered(true);webAppContext.setParentLoaderPriority(true);server.setHandler(webAppContext);try{server.start();}catch(Exception?e){}}這里我們按照web應用的標準規范建立文件夾WebContent、WEB-INF、以及web.xml,web.xml也要按規定格式寫,哪怕最簡單只寫一個段落
<welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.jsp</welcome-file> </welcome-file-list>啟動后在瀏覽器執行jsp頁面,發現仍然報錯:JSP support not configured
查了很久原因,發現是這樣,我引入jetty包的時候是用eclipse里的plugins目錄下的幾個jetty jar文件,這是不夠的。只得下了一個完整的jetty,解壓后引入其中lib/jsp目錄下的所有jar文件。再執行,還是報錯,不過這次變了:A full JDK(not just JRE) is required。原因是jsp需要編譯成隱含的servlet才能執行,所有需要完整jdk。這個解決辦法就比較簡單了——Run Configuration,選擇JRE,Alternate JRE、Installed JREs,然后Add一個新JRE,并指向一個jdk目錄就可以了。
經過一番折騰,終于使得內嵌的jetty可以解析jsp文件了。
轉載于:https://blog.51cto.com/6738767/1614226
總結
以上是生活随笔為你收集整理的使内嵌式jetty服务器支持jsp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .net framework 25007
- 下一篇: Linux手动添加用户、相关文件说明