我想在java主应用程序中使用嵌入式Jetty进行快速开发。对Jetty来说,我刚开始看一些关于Tuts和示例的内容,这就是我放在一起的内容:
public class JettyTest {
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
server.dumpStdErr();
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(HelloServlet.class, "/*");
server.setHandler(handler);
server.start();
server.join();
}
}
class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletResponse httpRes = (HttpServletResponse) res;
httpRes.setContentType("text/html");
httpRes.setStatus(HttpServletResponse.SC_OK);
httpRes.getWriter().println("<h1>Hello..</h1>");
}
}
这就是pom的依赖关系:
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!-- it is 3.1.0 version -->
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.15.v20160210</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.15.v20160210</version>
</dependency>
</dependencies>
当我运行时,我在控制台上获得了不那么有前途的输出:
org.eclipse.jetty.server.Server@58651fd0 - STOPPED
+? qtp1355316001{STOPPED,8<=0<=200,i=0,q=0} - STOPPED
+? ServerConnector@31ef45e3{HTTP/1.1}{0.0.0.0:8080} - STOPPED
| +~ org.eclipse.jetty.server.Server@58651fd0 - STOPPED
| +~ qtp1355316001{STOPPED,8<=0<=200,i=0,q=0} - STOPPED
| +?
org.eclipse.jetty.util.thread.ScheduledExecutorScheduler@754ba872 - STOPPED
| +- org.eclipse.jetty.io.ArrayByteBufferPool@598067a5
| +? HttpConnectionFactory@343f4d3d{HTTP/1.1} - STOPPED
| | +- HttpConfiguration@53b32d7{32768/8192,8192/8192,https://:0,[]}
| += org.eclipse.jetty.server.ServerConnector$ServerConnectorManager@589838eb - STOPPED
| +- null
| +- null
| +- null
| +- null
|
+> sun.misc.Launcher$AppClassLoader@18b4aac2
...
当我尝试点击localhost:8080
时,我得到了这个:
javax.servlet.ServletException: edu.jetty.exp.HelloServlet-6fc6f14e@23282359==edu.jetty.exp.HelloServlet,-1,false
我错过了什么?
答案 0 :(得分:1)
不要直接使用ServletHandler
,使用ServletContextHandler
并将servlet添加到其中。
至于代码示例,仅stackoverflow.com上就有数千个示例,甚至更多其他网站上的示例。
一些亮点:
examples/embedded
目录 - https://github.com/eclipse/jetty.project/tree/jetty-9.4.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded 此外,service(ServletRequest, ServletResponse)
方法是一个非常低级别的API(甚至不是HTTP!),很少在复杂库之外使用。