使用Guice Servlet和Jetty将路径映射到servlet而不使用web.xml

我正在努力让Guice Servlet工作来配置Jetty如何在这个简单的情况下为静态页面提供Web请求.

我创建了一个简单的应用程序,它应该映射两个不同的请求,一个使用GuiceServlet,另一个不使用.后者工作,而GuiceServlet映射一个返回404错误.

有小费吗?我正在使用:JDK 1.7.0_15; eclipse.jetty.jetty-servlet 8.1.9.v20130131; guice-servlet 3.0.谢谢.

public class Main {
    public static void main(String... args) {
        Guice.createInjector().getInstance(Main.class).start();
    }

    public void start() {
        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
        handler.addEventListener(new MyGuiceServletConfig());
        handler.addServlet(MyServlet.class, "/non-guice");
        server.setHandler(handler);
        try {
            server.start();
            server.join();
        } catch (Exception e) {
            e.printStackTrace();
        }       
    }
}

public class MyGuiceServletConfig extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                System.out.println("MyGSC->getInjector->configureServlets"); //I'm seeing this in the console...
                serve("/guice").with(MyServlet.class);
            }
        });
    }
}

@Singleton
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("Hello!\nYour path is: " + request.getServletPath());        
    }
}

除此之外,创建各种喷射器的最佳方法是什么?我有这样的main(..)结构,所以我可以插入其他模块,让我在MyGuiceServletConfig中指定MyServletModule,就像我在某处看到的那样 – 这是正确的吗?

解决方法:

我最终能够以一种有效的方式更简单.为“/”路径添加DefaultServlet是必要的:

public class MyMain {
    public static void main(String... args) throws Exception {
        Guice.createInjector(new MyServletModule());
        Server server = new Server(8080);    
        ServletContextHandler handler = 
            new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
        handler.addFilter(GuiceFilter.class, "/*", allOf(DispatcherType.class));
        handler.addServlet(DefaultServlet.class, "/");
        server.start();
    }
}

@Singleton
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("Hello!\nYour path is: " + request.getServletPath());        
    }
}

public class MyServletModule extends ServletModule {
    @Override
    protected void configureServlets() {
        serve("/guice").with(MyServlet.class);
    }
}
上一篇:我可以在不使用Apache和shibd的情况下在我的Java Webapp中集成Shibboleth SSO吗?


下一篇:activemq安装