Sanket Pipariya
Sanket Pipariya

Reputation: 89

script inside scriptlet - bad practice how to avoid

i am working on a legacy project where i have seen below piece of code. I know it is a bad practice to use script inside scriptlet. Regarding this , i have few confusion in mind.

  1. what i believe is scriptlet is executed before page loads, so if below if condition is true then ShowBookReference() function call is a part of an Html page, but my question is when page is rendered should this function call happens or not ?

 <% if (refLinkTerm != null) { %>
          <script Language="javascript">
          ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
          </script>
    <%}%>

  1. How to avoid this kind of practice ?

Please share your thoughts.

Upvotes: 0

Views: 894

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

In terms of JSP, Its usual to use scriptlets to assign value to JS.

But as you've mentioned that it runs before the page load, so it's good to run the function on window.onload.

<script type="text/javascript">
      window.onload = function() {
          ShowBookReference('<%=sub2ndNavMenu%>', '<%=refLinkTerm%>', <%=String.valueOf(searchType)%>, <%=String.valueOf(codeType)%>)
       }
</script>

In case you're referring some DOM elements inside ShowBookReference function, it may not be available so run it on page load.

Else you can use UI frameworks like JSF which provides you tags to bind java values to UI easily.

Upvotes: 2

Use an MVC framework such as Spring MVC. In these frameworks, you fill in a Java object (or map of objects) with the values for the page to display, and then the page just fills in placeholders with those values.

Upvotes: 2

Related Questions