码迷,mamicode.com
首页 > Web开发 > 详细

Guice 学习(九) WEB AND SERVLET

时间:2015-07-02 12:08:29      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

1、新建web工程,导入JAR包

技术分享

2、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>GuiceWeb</display-name>

    <listener>
        <listener-class>com.guice.web.listener.MyGuiceServletContextListener</listener-class>
    </listener>
    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>



</web-app>

3、自定义监听器

package com.guice.web.listener;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.guice.web.servlet.HelloWorldServlet;

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

4、新建servlet

package com.guice.web.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.guice.web.service.HelloWorld;

/**
 * TODO :每个servlet必须是单例的
 * 
 * @author E468380
 */
@Singleton
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Hello , Guice !" + new Date());


    }

}

5、运行tomcat服务器

技术分享

6、注入服务

新建service接口

package com.guice.web.service;

import java.io.IOException;

import com.google.inject.ImplementedBy;

@ImplementedBy(HelloWorldImpl.class)
public interface HelloWorld {
    void execute() throws IOException;
}

新建实现类

package com.guice.web.service;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;

public class HelloWorldImpl implements HelloWorld {

    private HttpServletRequest request;
    private HttpServletResponse response;

    @Inject
    public HelloWorldImpl(HttpServletRequest request, HttpServletResponse response) {
        super();
        this.request = request;
        this.response = response;
    }

    public void execute() throws IOException {
        String name = request.getParameter("user");
        if (name == null || name.length() < 1)
            name = "Guest";
        response.getWriter().append(
                String.format("Hello, %s. %s -> sessionId=%s,hashCode=%d ", name, new Date(), request.getSession().getId(), hashCode()));
    }
}

修改servlet

package com.guice.web.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.guice.web.service.HelloWorld;

/**
 * TODO :每个servlet必须是单例的
 * 
 * @author E468380
 */
@Singleton
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Inject
    private Injector inj;// 自动注入Injector对象,然后通过Inject对象获取我们的服务,

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Hello , Guice !" + new Date());
        inj.getInstance(HelloWorld.class).execute();
        inj.getInstance(HelloWorld.class).execute();

    }

}

输出

Hello , Guice !Thu Jul 02 10:38:27 CST 2015
Hello, Guest. Thu Jul 02 10:38:27 CST 2015 -> sessionId=C038A844F4C2C8259E06479AA59F0CC7,hashCode=1240584990 
Hello, Guest. Thu Jul 02 10:38:27 CST 2015 -> sessionId=C038A844F4C2C8259E06479AA59F0CC7,hashCode=593198207 

由上可知:sessionId是一样的,但是hashcode值不同,与原例不符,那是因为在
原文示例中(参考这里)将HelloWorldImpl类上标明注解:@RequestScoped ,但是程序运行会出如下错误:

HTTP Status 500 - Filter execution threw an exception

type Exception report

message Filter execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Filter execution threw an exception

root cause

java.lang.NoSuchMethodError: com.google.inject.Scopes.isCircularProxy(Ljava/lang/Object;)Z
    com.google.inject.servlet.ServletScopes$2$1.get(ServletScopes.java:121)
    com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
    com.google.inject.internal.InjectorImpl$3.get(InjectorImpl.java:737)
    com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:978)
    com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)
    com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:974)
    com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)
    com.guice.web.servlet.HelloWorldServlet.doGet(HelloWorldServlet.java:34)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    com.google.inject.servlet.ServletDefinition.doServiceImpl(ServletDefinition.java:278)
    com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:268)
    com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:180)
    com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:93)
    com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:120)
    com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:132)
    com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:129)
    com.google.inject.servlet.GuiceFilter$Context.call(GuiceFilter.java:206)
    com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:129)

我也不清楚这是为什么,如果有人知道,烦请告知,谢谢!

Guice 学习(九) WEB AND SERVLET

标签:

原文地址:http://blog.csdn.net/u010834071/article/details/46723955

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!