Cristian Matthias Ambæk Cristian Matthias Ambæk - 7 months ago 21
Java Question

Load dynamic .jsp page on pageload with specific servlet

I would like to create a .jsp page that is to be loaded on pageload, but the content of the page is dynamically created by calling my local database.

My question is. When a user request the index.jsp page, how do i "say".
Before displaying the index.jsp page call servletX to get content, and send this back to the index.jsp page?

I have mapping my jsp and servlet together as follows

<servlet>
<servlet-name>intname</servlet-name>
<servlet-class>ServletBooks</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>intname</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>


But dont know how i send the dispather, back to self?
getServletContext().getRequestDispatcher(???).forward(request, response);

Edit.
Okey so now the site works as follows.
I request the index.jsp page, which is mapped in the web.xml to a servlet.
But if i set the requestDispatcher to the index.jsp page, the whole site hangs. If i set it to another page like result1.jsp it works fine. Execpt it isint the index page displaying the content.

How do i say to the servlet, send output to initiator?

Answer

But if i set the requestDispatcher to the index.jsp page, the whole site hangs. If i set it to another page like result1.jsp it works fine.

Yes, because it is obviously going into an infinite loop as index.jsp is mapped to the Servlet you are forwarding from.

You need to have a look at the ModelViewController pattern. Essentially you never allow direct access to JSP but route through a controller, in your case a simple Servlet which will load any data required for the view and then dispatch to the view for rendering.

<servlet>
    <servlet-name>intname</servlet-name>
    <servlet-class>ServletBooks</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>intname</servlet-name>
    <url-pattern>/loadBooks.do</url-pattern>
</servlet-mapping>

<!-- If you are on Tomcat set a Default page if root of webapp requested -->
<welcome-file-list>
    <welcome-file>loadBooks.do</welcome-file>
</welcome-file-list>

In your servlet load the data and now forward to index.jsp.

http://www.thejavageek.com/2013/08/11/mvc-architecture-with-servlets-and-jsp/