首先给出一个简单的内嵌Jetty程序

package mp.http.server;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

/**
 *
 * @author zkpursuit
 */
public class HttpServer {

    public static void main(String[] args) throws Exception {
        WebAppContext webapp_context = new WebAppContext();
        webapp_context.setDescriptor("./src/webapp/WEB-INF/web.xml");
        webapp_context.setResourceBase("./src/webapp");
        webapp_context.setContextPath("/");
        webapp_context.setParentLoaderPriority(true);
        webapp_context.setClassLoader(Thread.currentThread().getContextClassLoader());
        Server server = new Server(8080);
        server.setStopAtShutdown(true);
        server.setHandler(webapp_context);
        server.start();
        server.join();
    }

}

 

WebAppContext的基类是ServletContextHandler,所以它天生支持Servlet,可是JSP呢?JSP最终会编译成Servlet运行的,网上一查,最新版的Jetty默认支持jsp,可是我测试的时候直接报错

org.apache.jasper.JasperException: Unable to compile class for JSP

 

应该是我理解有误,默认支持jsp的应该是Jetty自带的那个默认Web/Servlet容器吧,我也没测试,无法下结论。

下面继续讨论怎么让上面的代码运行支持jsp。

从上面的错误可以看出是jsp文件未被编译,而把jsp编译为Servlet需要额外的库,从下载的jetty的lib文件夹中,包含apache-jsp文件夹,把其中所有jar包导入,并加入

webapp_context.addServlet(JettyJspServlet.class, "*.jsp");

再次运行,还是报那个不能编译的错误,这下就郁闷了,接着查资料,终于找到下面的方法了

public static class JspStarter extends AbstractLifeCycle implements ServletContextHandler.ServletContainerInitializerCaller {

        JettyJasperInitializer sci;
        ServletContextHandler context;

        public JspStarter(ServletContextHandler context) {
            this.sci = new JettyJasperInitializer();
            this.context = context;
            this.context.setAttribute("org.apache.tomcat.JarScanner", new StandardJarScanner());
        }

        @Override
        protected void doStart() throws Exception {
            ClassLoader old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(context.getClassLoader());
            try {
                sci.onStartup(null, context.getServletContext());
                super.doStart();
            } finally {
                Thread.currentThread().setContextClassLoader(old);
            }
        }
    }

 

接着使用这个类,在最上面的main方法中加入

webapp_context.addBean(new JspStarter(webapp_context));
webapp_context.addServlet(JettyJspServlet.class, "*.jsp");

再次运行,我能呵呵了,终于能运行jsp了,大功告成

转载于:https://my.oschina.net/zkpursuit/blog/868725

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐