我在使用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(..)结构化如下,以便我可以插入其他模块,留下MyServletModule在MyGuiceServletConfig中指定,就像我在某个地方看到的那样-这是正确的吗?
FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));
handler.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));
- neuronotic