使內嵌式jetty伺服器支援jsp,jettyjsp

來源:互聯網
上載者:User

使內嵌式jetty伺服器支援jsp,jettyjsp

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檔案了。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.