应用程序启动时启动servlet

IBR*_*BRA 5 java web.xml servlets servlet-listeners

我想在加载jsp页面之前启动servlet类,因为我需要在jsp页面中填充数据库中的一些数据.web.xml中的Servlet映射

    <servlet>
        <servlet-name>Index</servlet-name>
        <servlet-class>com.Teklabz.Servlets.IndexServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Index</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

但它没有用,当跟踪代码时它永远不会到达servlet类.另外我试图像这个链接一样使用ServletContextListener ,但我遇到了同样的问题.

监听代码:

public class ServletListener implements ServletContextListener{

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
Run Code Online (Sandbox Code Playgroud)

web.xml代码:

    <listener>
        <listener-class>com.techlabz.listener.ServletListener</listener-class>
    </listener>
Run Code Online (Sandbox Code Playgroud)

我不知道做错了什么.

ami*_*ngh 3

有多种方法可以实现这一目标..

  1. 您可以在服务方法中填充数据com.Teklabz.Servlets.IndexServlet,然后在属性中设置数据request,然后转发到该方法jsp
  2. 如果你想使用,那么你可以在servlet的方法loadonstartiup中填充db中的数据,然后将其设置在某个可访问的范围内,并通过直接访问jsp从该范围中获取数据。com.Teklabz.Servlets.IndexServletinit(request,session,context)
  3. 在侦听器中,您也可以执行此操作,但在这种情况下,您还需要在某个范围内设置数据。