如何在脚本中获取Java代码的值

版权声明:欢迎转载大宇的博客,转载请注明出处: https://blog.csdn.net/yanluandai1985/article/details/83058749

        把数据存放到 Session中,然后在页面 使用 <%%> 写Java脚本片段。最后再取出Java对象中的数据。

        突然觉得自己眼高手低了,以前最最基础的JavaWeb已经忘记,那些最基本的Servlet的生命周期也快忘光,我记得有4个域。

        是时候去温故一下了。

        //创建传输数据的Bean
        WebApplicationObject bean = new WebApplicationObject();
        //设置bean的属性
        bean.setId(id);
        bean.setName(name);
        //存放到session中
        session.setAttribute(WEB_APPLICATION_OBJECT, bean);

       在页面上的JS里面请求数据,示例如下:

<script type="text/javascript">
    <!-- 先通过Java脚本片段获取存放在Session中的Bean -->
    <%
    final WebApplicationObject bean  = 
                 (WebApplicationObject)session.getAttribute(WEB_APPLICATION_OBJECT);
    %>

    <!-- 获取Bean的Id,记得加上此括号,不确定的话直接复制也行,亲测有效 -->
    var id   = '<%=(bean.getId())%>';  

    <!-- 获取Bean的Name -->
    var name = '<%=(bean.getName())%>';


</script>
<script type="text/javascript">
    alert(id );
    alert(name);
</script>

猜你喜欢

转载自blog.csdn.net/yanluandai1985/article/details/83058749