Printing a java scriptlet variable as if it is a J

2020-05-06 13:21发布

问题:

hello i need to output a java variable inside a javascript call inside a tag inside a jsp !

for example:

 <% String param = "hello";%>

<dmf:checkbox  name="checkbox"
  onclick = "selectAll(<%=param%>)"
/>

the javascript generated is:

selectAll(<%=param%>),this); but I actually want something like

selectAllCheckBoxes(Hello),this);

回答1:

That's not escaping. That's just printing a scriptlet variable as if it is a JavaScript variable.

Besides, your examples are confusing, they doesn't match each other and the Javascript code is syntactically invalid. I can at least tell that JavaScript string variables are to be surrounded by quotes. If you want to end up with

selectAllCheckBoxes('Hello', this);

where Hello should be obtained as a value of the scriptlet local name variable (the param is a reserved variable name, you shouldn't use it yourself), then you need to do

selectAllCheckBoxes('<%= name %>', this);

In the same way, if you want to end up with

onclick="selectAll('Hello')"

you need to do

onclick="selectAll('<%= name %>')"

That said, I strongly recommend you to stop using the old fashioned scriptlets which are been discouraged since more than a decade. JSP programmers were been recommended to use taglibs and EL only to make the JSP code more clean and robust and better maintainable. You can use taglibs such as JSTL to control the flow in the JSP page and you can use EL to access the "back-end" data. Your example can be replaced by:

<c:set var="name" value="Hello" />

...

selectAllCheckBoxes('${name}', this);


回答2:

Generate the whole attribute value with a scriptlet, like this:

<dmf:checkbox  name="checkbox"
   onclick = "<%= "selectAll(" + param + ")" %>" />


回答3:

maybe you are trying to achieve this?

var myVar = '<%= (String)request.getParameter("tab") %>'; 
loadtabs(myVar);