使内嵌式jetty服务器支持jsp

时间:2022-09-25 15:35:59

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文件了。

本文出自 “空空如也” 博客,请务必保留此出处http://6738767.blog.51cto.com/6728767/1614226