题
我试图使用restlet.org库来构建一个RESTful web界面,我已经注意到,不同于它的servlet的对手,它没有补充GenericServlet.init()。
短构建另一个servlet做我的启动逻辑的,有没有内置的方式,以避免构建我的数据库工厂和喜欢上了第一个请求(以及所有相称锁定我必须做些什么来避免多次初始化)?
解决方案
您想在servlet容器中运行呢?如果不是,文档展示了如何运行单机:
public static void main(String[] args) throws Exception {
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);
// Attach the sample application.
component.getDefaultHost().attach("/firstSteps",
new FirstStepsApplication());
// Start the component.
component.start();
}
您当然可以做初始化那里。
如果你想使用servlet的做法,尝试写一个新的servlet和扩展他们的。实现你的init方法并调用一个超类。
其他提示
如果你真的想这样做在servlet环境中,你可能有你的web应用中两个servlet:一个用于应用的Restlet /组件,一个用于初始化,使用load-on-startup
(你不一定会映射到任何URL,据我所知,你不必)。这样,您就不必子类org.restlet.ext.servlet.ServerServlet
。我想,这可能是更容易,因为这初始化servlet的将只包含init()
,但这只是将事情不依赖于应用程序的Restlet /组件工作,首先进行初始化。
<context-param>
<param-name>org.restlet.clients</param-name>
<param-value>HTTP HTTPS CLAP FILE</param-value>
</context-param>
<servlet>
<servlet-name>ExampleInit</servlet-name>
<servlet-class>example.TestInitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
<init-param>
<param-name>org.restlet.application</param-name>
<param-value>example.TestApplication</param-value>
</init-param>
<init-param>
<param-name>org.restlet.autoWire</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
可替换地(或者可能在补充本),我倾向于使用JNDI用于初始化数据库连接和几个其他配置设置。这也允许我保持相同的配置和装载机构,我是否使用的Restlet独立服务器或的Restlet web应用程序内。
例如,对于一个servlet容器(例如码头或Tomcat)内的部署,我使用容器的JNDI配置,但对于本地测试(使用独立的Restlet应用程序),我使用的是Jetty JNDI上下文工厂(你可以得到从码头的其余部分的单独罐)。
不隶属于 StackOverflow