【问题标题】:Jersey servlet class is constructed with every requestJersey servlet 类由每个请求构建
【发布时间】:2017-12-02 02:08:31
【问题描述】:

我正在做一个非常简单的 tomcat 和 jersey servlet 设置。我刚刚注意到为每个请求构建的 servlet 类。我所读到的关于 servlet 的内容是它们是 init() 一次、 service() 多次和 destroy() 一次。为什么我的设置不是这样。

下面是我的 web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>contact-dropbox-servlet</servlet-name>
        <servlet-class>
            org.glassfish.jersey.servlet.ServletContainer
        </servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.inbhiwadi.services</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>contact-dropbox-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

我的 servlet 入口类如下所示:

@Path("/contact")
@Slf4j
public class ContactDropboxService {

    private ContactDAO contactDAO;

    private NotificationPublisher notificationPublisher;

    public ContactDropboxService() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
        this.contactDAO = (ContactDAO) context.getBean("contactDAO");
        this.notificationPublisher = (NotificationPublisher) context.getBean("notificationPublisher");
        log.debug("ContactDropboxService constructed one more time");
    }

    @GET
    public String greet() {
        log.info("Welcome to InBhiwadi contact services!");
        return "Welcome to InBhiwadi contact services";
    }

    @POST
    @Path("/drop")
    public Response create(Contact contact) {

        log.debug("Received contact is : [{}]", contact.toString());
        contactDAO.create(contact);
        notificationPublisher.publish(contact.toString());
        return Response.accepted("Contact dropped in box").build();
    }
}

我应该怎么做才能让 ContactDropboxService 的单个实例服务多个请求?

【问题讨论】:

    标签: java tomcat servlets glassfish servlet-container


    【解决方案1】:

    默认情况下,Jersey 将根据请求实例化资源类。如果您只想拥有一个资源类实例,则应使用@Singleton 对其进行注释。有关更多详细信息,您可以查看此 SO question

    【讨论】:

    • 我很好奇它将如何处理并发请求。如果在第一个请求之前出现另一个请求,是否会分叉多个线程。如果是,那么是否要手动处理并发?
    猜你喜欢
    • 2017-05-17
    • 2015-07-13
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多