Avoid Scriptlets in Jsp for displaying data on page load

妖精的绣舞 提交于 2020-01-07 04:08:43

问题


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.


回答1:


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



回答2:


I think using EL in combination with JSTL can help you in the most common situations. If this is not enough you can write EL functions or your own custom tags.



来源:https://stackoverflow.com/questions/6637331/avoid-scriptlets-in-jsp-for-displaying-data-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!