Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting the servlet when the application startup

I want to starting by fireing the servlet class before loading a jsp page, because i need to populate some data from the database in a jsp page. Servlet mapping in web.xml

    <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>

but it didn't work, when tracing the code it's never reach the servlet class. Also i was trying to use ServletContextListener like this link, but I faced the same problem.

listener code:

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.");
    }
}

web.xml code:

    <listener>
        <listener-class>com.techlabz.listener.ServletListener</listener-class>
    </listener>

I don't know what am doing wrong.

like image 581
IBRA Avatar asked Oct 22 '22 20:10

IBRA


1 Answers

There are number of ways you can achieve this ..

  1. Either you can populate the data in service method com.Teklabz.Servlets.IndexServlet and then set the data in request attribute and then forward to that jsp.
  2. If you want to use loadonstartiup then you can populate the data from db in com.Teklabz.Servlets.IndexServlet servlet's init method and then set it in some accessible scope(request,session,context) and by direct accessing jsp get the data from that scope.
  3. In listener also you can do this but in that case also you need to set the data in some scope.
like image 188
amicngh Avatar answered Oct 24 '22 17:10

amicngh