Search code examples
formsjspservletsscopescriptlet

Avoid Scriptlets in Jsp for displaying data on page load


I realize that when you submit the form in a jsp, in the mapped servlet you can get the desired data, set it in the proper scope(say request) and forward it to jsp like this:

request.setAttribute("myList", myList); // Store list in request scope.
request.getRequestDispatcher("/index.jsp").forward(request, response);

However am wondering for pages which doesn't have a form or in other words we want to display data as soon as page loads, how can we efficiently load the data without using scriptlets like

<%= myBean.populateData("String Argument_1")%>

Would highly appreciate if anyone can provide any recommendations around the same.


Solution

  • The fact that the request comes from a form or not doesn't change anything. The servlet receives a request, and then can do some processing and forward to a JSP:

    1. servlet gets request parameters
    2. servlets uses those parameters to get requested data from a database, and populate some beans with said data. It may also build some beans from scratch, to display a form with default values
    3. servlet puts those beans in request attributes
    4. servlet forwards to a JSP
    5. JSP avoids using scriptlets and rather uses JSP EL, the JSTL and custom tags to display the information stored in the beans in request scope