2017-12-06 6 views
1

私は、Javaメインアプリケーションに埋め込まれたJettyを使用して、すばやく開発したいと考えています。桟橋に全く新しい私はいくつかのtutsと例を見ることで開始し、ここで私は一緒に置くものです:埋め込みサーブレットコンテナとしてJettyを使用しようとしています

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> 

私はこれをない得たことを実行しますその有望なコンソールに出力:

[email protected] - STOPPED 
+? qtp1355316001{STOPPED,8<=0<=200,i=0,q=0} - STOPPED 
+? [email protected]{HTTP/1.1}{0.0.0.0:8080} - STOPPED 
| +~ [email protected] - STOPPED 
| +~ qtp1355316001{STOPPED,8<=0<=200,i=0,q=0} - STOPPED 
| +? 
org.eclipse.jett[email protected] - STOPPED 
| +- [email protected] 
| +? [email protected]{HTTP/1.1} - STOPPED 
| | +- [email protected]{32768/8192,8192/8192,https://:0,[]} 
| += [email protected]589838eb - STOPPED 
|  +- null 
|  +- null 
|  +- null 
|  +- null 
| 
+> [email protected] 
... 

と私はlocalhost:8080をヒットしようとすると、私はこれを取得:

javax.servlet.ServletException: [email protected]==edu.jetty.exp.HelloServlet,-1,false 

私は何が欠けていますか?

+0

知らんに長いの回答を参照してください。私のために働く。 :) – Stewart

+0

私は以前のバージョンのJetty( '8.1.22.v20160922')を使用していて、サーブレットマッピングを経由する代わりに' Handler'を直接設定していました – Stewart

答えて

0

ServletHandlerを直接使用しないでください。ServletContextHandlerを使用して、そのサーブレットを追加してください。

コード例では、他のWebサイトでもstackoverflow.comだけで何千ものサンプルが利用できます。

いくつかのハイライト:

また、service(ServletRequest, ServletResponse)方法は非常に低レベルのAPI(そのていなくてもHTTPです!)、複雑なライブラリの外ではめったに使用されません。

サーブレットAPIを初めて使用する場合は、doGet()doPost()のように、さまざまなdo*()メソッドを代わりに使用することを検討してください。

doGet and doPost in Servlets

関連する問題