我正在尝试JAX-RS,在Tomcat上部署。它基本上是:
@Path("/hello")
@Produces({"text/plain"})
public class Hellohandler {
@GET
public String hello() {
return "Hello World";
}
}
有没有办法在我的JAX-RS资源中获得ServletContext
?
发布于 2009-11-29 13:55:11
此外,@Resource
注释可能不起作用。尝尝这个
@javax.ws.rs.core.Context
ServletContext context;
直到您点击服务方法,注入才会发生
public class MyService {
@Context ServletContext context;
public MyService() {
print("Constructor " + context); // null here
}
@GET
@Path("/thing") {
print("in wizard service " + context); // available here
发布于 2015-04-09 19:25:56
在实现ServletContextListener时,servlet上下文也可用。这使得在启动时加载连接字符串等参数变得很容易。您可以在web.xml中定义在web应用程序启动时加载ServletContextListener的侦听器类。
在web.xml文件中,添加<listener>
和<context-param>
标记。<listener>
指定在启动时调用的类。<context-param>
标签定义了web应用程序中可用的上下文参数。
首先,在web.xml文件中包含<listener>
和<context-param>
标记:
<web-app>
<!-- ... -->
<listener>
<listener-class>com.your.package.ServletContextClass</listener-class>
</listener>
<!-- Init parameters for db connection -->
<context-param>
<param-name>your_param</param-name>
<param-value>your_param_value</param-value>
</context-param>
<!-- ... -->
</web-app>
现在创建servlet上下文类,如下所示。
public class ServletContextClass implements ServletContextListener
{
public void contextInitialized(ServletContextEvent arg0)
{
//use the ServletContextEvent argument to access the
//parameter from the context-param
String my_param = arg0.getServletContext().getInitParameter("your_param");
}//end contextInitialized method
@Override
public void contextDestroyed(ServletContextEvent arg0)
{ }//end constextDestroyed method
}
现在,您可以选择将哪个静态变量分配给您已读取的参数。这允许您在启动时读取参数一次,并通过分配给它的静态变量多次重用。
发布于 2009-11-29 12:37:54
只需像这样使用资源注入,
@Resource ServletContext servletContext;
https://stackoverflow.com/questions/1814517
复制相似问题