3

My code currently looks like this

<%
    if (request != null) {
        bustOut;
    }
%>

<script language="javascript">
function bustOut(){
   var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
}
</script>

How do I call the javascript function inside the Java code? Or is that not possible?

Jin
  • 6,055
  • 2
  • 39
  • 72

2 Answers2

5

JSP runs at webserver and generates/produces HTML/CSS/JS code upon a webbrowser request. Webserver sends HTML/CSS/JS to webbrowser. Webbrowser runs HTML/CSS/JS. So, you just have to let JSP print it literally as JS code.

<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    <% 
        if (foo != null) { 
            out.print("bustOut();");
        }
    %>
</script>

or, better, with EL

<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    ${not empty foo ? 'bustOut();' : ''}
</script>

(note that I changed the attribute name to foo because request stands for HttpServletRequest which might confuse others since this is never null)

Either way, the generated HTML (which you should see by opening page in browser, rightclicking it and choosing View Source) should look like this when the condition was true:

<script language="javascript">
    function bustOut(){
       var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes"); 
    }
    bustOut();
</script>

Does it now turn on a light bulb above your head?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

You can't call javascript functions from java

Your java code is executed on the server, and the javascript - on the client.

What you seem to need is conditionally open a new window on document load. For that:

<c:if test="${shouldDisplayWindow}">
     $(document).ready(function() {
         bustOut();
     });
</c:if>

(that's jQuery above for detecting document load. You can replace it with pure javascript - window.onload = function() {..} or document.onload = function() {..} I think)

Note that request != null is meaningless condition - the request is never null in a JSP.

And finally - use jstl tags (like I showed) and not java code (scriptlets).

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140