在jsp中通过java访问javascript

Jin*_*Jin 3 javascript java jsp

我的代码目前看起来像这样

<%
    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>
Run Code Online (Sandbox Code Playgroud)

如何调用Java代码中的javascript函数?或者那是不可能的?

Bal*_*usC 5

JSP在webserver上运行,并在webbrowser请求时生成/生成HTML/CSS/JS代码.Web服务器将HTML/CSS/JS发送到webbrowser.Webbrowser运行HTML/CSS/JS.所以,你只需要让JSP打印成字面为JS代码.

<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>
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,用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>
Run Code Online (Sandbox Code Playgroud)

(请注意,我将属性名称更改为foo因为request代表HttpServletRequest可能会使其他人感到困惑,因为这永远不会null)

无论哪种方式,当条件为真时,生成的HTML(您应该通过在浏览器中打开页面,右键单击它并选择" 查看源")应该看起来像这样:

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

它现在打开你头顶的灯泡吗?