Get the value of a variable in java in js in jsp page

Assign values ​​to js variables by means of <%=java variable%>.
1. Define a java variable
<%
String a = "222";//Define a java variable of string type
%>
2. Output to js
var k = <%=a%>; Output the variable value to k, this is k is 222
supplement:
<% %> The jsp code inside the logo can be defined, and java variables can be defined
<%=variable %> Output java variable information

1. The js variable gets the variable value of the java code in the jsp page.
Method: var JS variable name = <%=JAVA variable name%>
We often write js files and jsp files separately. In js files, the above method does not seem to work.
It can also be solved by a workaround:
a.jsp
<% String name = "zhangsan" %>
"

aa.js
var n = document.getElementById(‘a’).value;

It's also more convenient to do this with jquery

2. The java code gets the value of the js variable.
Description: In JSP; the Java part is executed on the server side; the js part is executed on the client's browser; the two are completely irrelevant. Therefore, it is not possible to call between js, java and HTML variables directly on the JSP page.
Workaround (solution): put the js variable into one of the form; take the variable from the form in the background and put it in the hidden field; then submit the form to the page that calls the variable. This page can be itself. The example is as follows:
bb.jsp page:
<% String test5 = (String)request.getAttribute("test4"); %>

var test1 = '111'; //Define js variable
document.form.test2.value = test1;
/ / Put the value of the js variable into a hidden field in the form
var formObj = document.getElementById('passForm');
formObj.submit();




Java code in the aa.jsp page:
<%
request.setCharacterEncoding("utf -8");
String txtMsg = request.getParameter("test2");
out.println(txtMsg);
%>
Note: If the same page passes values ​​to itself, aa.jsp and bb.jsp can be the same page.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325978936&siteId=291194637