简体   繁体   English

将Java变量从JSP提取到Script标记中

[英]Fetching Java variable from JSP into Script tag

I am writing a JSP and have the Java code written in the <code> tags. 我正在编写一个JSP,并在<code>标记中编写了Java代码。

I would like to use a Java variable which is inside the <code> tag, inside the script tag. 我想在<code>标记内,脚本标记内使用Java变量。

Example:- 例:-

  <html>
    <head>
    var myJSVar = $(myJavaVariable)//Something like this and this doesn't work
    </head>
    <body>
    <pre>
    <code>
     String myJavaVariable = "Sample String";
    </code>
    .....

Thanks!!!! 谢谢!!!!

Its not possible to get java variable inside a script. 无法在脚本中获取java变量。 you can set the values in to a HTML element using java after you have done that you can use <script> tag to access the values which is in HTML element 您可以在使用<script>标记访问HTML元素中的值之后,使用java将值设置为HTML元素

    <% String Name="myName"; %>
    <input type="text" name="Name" id="Name"  value="<%=Name%>" maxlength="50" />

using script tag to get the data in html element. 使用脚本标签获取html元素中的数据。

<script>              
    var name = document.getElementById('Name').value;
    <script>

<code> is not a tag used in HTML to write java code. <code>不是HTML中用于编写Java代码的标记。 so you cant do any coding inside a code tag anything you will write in there will be just interpreted on browser in the format of a code. 因此,您不能在代码标签内进行任何编码,而要在其中写入的任何内容都只会在浏览器中以代码格式进行解释。

changed the answer according to your comments.example on getting values as a json and converting them to java objects 根据您的注释更改了答案。有关将值作为json并将其转换为Java对象的示例

  String json = "{\"Name\":\"priyamal\",\"Mob\":\"077045\"}";
    ObjectMapper mapperobject = new ObjectMapper();
    Map<String, Object> javaobj = mapperobject.readValue(json, new TypeReference<Map<String,Object>>() { });
    out.println("MyName:" + javaobj.get("Name") + "Mobile:" + javaobj.get("Mob"));

First you have to declare , <% String myJavaVariable = "Sample String"; 首先,您必须声明<%String myJavaVariable =“ Sample String”; %> %>

Then in script, var myJSVar = "<%=myJavaVariable%>"; 然后在脚本中,var myJSVar =“ <%= myJavaVariable%>”;

There are two ways to use java variable on jsp 在jsp上使用java变量有两种方法

  1. ${message}
  2. <%String myVar="blabla";%>

Hope this is useful for you. 希望这对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM