原创

Guice整合guice-servlet进行web开发

1.创建一个mvn web工程

这个....用idea自己创建就行了

2.配置

1.在web.xml中配置Guice的拦截器

  <filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class><!--这个是guice servlet的拦截器-->
  </filter>
  <filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

guiceFilter将拦截所有web请求

2.配置Injector

"web.xml中添加下面三行"
  <listener>
    <listener-class>com.servlet.GuiceBootstrapServletConfigListener</listener-class><!--这个是用于注册module及servlet的-->
  </listener>

3.注册module及servlet

public class GuiceBootstrapServletConfigListener extends GuiceServletContextListener {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule(){
            protected void configureServlets() {
                serve("/Hello").with(Hello.class);
            }
        });
    }
}

4.写action,处理http请求

@Singleton
public class Hello extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Hello , Guice-servlet !" + new Date());
    }
}

至此全部配置完成 http://localhost:3001/guice-servlet/Hello 访问就好了
Guice Servlet扩展还有很多功能,详情搜索Guice文档

源码 https://github.com/Fireflyi/xiaoqingxin/tree/master/guice-servlet

正文到此结束
本文目录