Is it possible to write javascript with Java in a jsp - java

If I had code similar to the following, could I run it without any issues? I assume the Java will be run before the javascript, so the javascript won't have issues, but I haven't done this before:
<script type="text/javascript">
<% functThatOutputsJavascript() %>
</script>

This is very, very bad programming style, but yes, it is possible.
The code I am working on now has done some very similar stuff. I think you would actually want to do:
<script type="text/javascript">
<%= functThatOutputsJavascript() %>
</script>
And actually, you can do even worse, using Java conditionals to modify the Javascript output:
<script type="text/javascript">
while (i > 0) {
<% if (serverVar)) { %>
console.log("Server says yes!");
<% } else { %>
console.log("Server says no!");
<% } %>
}
</script>
This would then output this code if serverVar is true:
<script type="text/javascript">
while (i > 0) {
console.log("Server says yes!");
}
</script>
or this code if it is false:
<script type="text/javascript">
while (i > 0) {
console.log("Server says no!");
}
</script>
This is horrible coding style, and I hope you won't do it in practice! If you are wondering how to avoid writing code like this, check out this question: How to avoid Java code in JSP files?
A general suggestion would be to use JSP EL (JSP Expression Language) to set server side variables into your Javascript, and then write all of your logic in Javascript.

Related

java controller to html if alert

i have a problem using alert in html.
I have a controller in Java that sends
model.addAttribute("borrowedAlready",1);
and I need to take it from html.
here's code i have but doesn't seem to work.
<div>
<script type="text/javascript">
var borrowed = '${borrowedAlready}';
if(borrowed== 1){
alert("Borrwed Already.");
}
</script>
</div>
Need help

Evaluate JavaScript within a HTML with Java

I want to get the generated html output from a javascript within a given html string in java.
First, i just don't know, how to set the full html and javascript in code. all i've seen is, that i can give some small javascript to java, invoke some parameters and get some output.
Is there a way to set a html-string as context??
The example (taken from another thread):
<html>
<head><title> test </title>
<body></body>
<div>Welcome</div>
<style type="text/css">
.title{
color:red
}
</style>
<script type="text/javascript">
var i=0;
for (i=0;i < 5;i++){
document.writeln("<div class='title'>" + i + "</div>");
}
</script>
</html>
What i want to do is, to pass this html code into javascript context and call the function (actually there is no function, but i know how to call javascripts functions)
then, Rendering in a browser will give you this html back:
<html>
<head><title> test </title>
<body></body>
<div>Welcome</div>
<style type="text/css">
.title{
color:red
}
</style>
<script type="text/javascript">
var i=0;
for (i=0;i < 5;i++){
document.writeln("<div class='title'>" + i + "</div>");
}
</script>
<div class="title">0</div>
<div class="title">1</div>
<div class="title">2</div>
<div class="title">3</div>
<div class="title">4</div>
</html>
So, the basic output on the javascripting mangere is simple:
Welcome
0
1
2
3
4
I don't want to render any of these elements, i am simply interested in getting the html output.
I'm not sure how to perform this task.
I want to keep it simple, no frameworks at all, just a simple mechanic to pass html-code and javafunctions into the javascriptengine, evaluate it and get the html back, just like the browsers getting more html-code back (usually).
there's no rendering intended.
Have you checked out the new Nashorn javascript engine in Java 8?
I havent actually used it yet, so I am not sure if you can just pass it an html string or if you will need to separate the JS and HTML, but worth taking a look.
Theres a basic tutorial here:
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
If not, there is always PhantomJS that you can use to execute Javascript. There are some examples here:
http://phantomjs.org/quick-start.html
Looks like there are some useful functions like page loading and code evaluating that you may be able to use.

JSTL for each, var contains square brackets

I have a HashSet of Strings, which is made with the following code:
Set<String> scripts = new HashSet<>();
String contextPath = request.getContextPath();
scripts.add(contextPath + "/resources/scripts/jquery.cycle2.js");
scripts.add(contextPath + "/resources/scripts/jquery.cycle2.center.js");
scripts.add(contextPath + "/resources/scripts/slideshow.js");
request.setAttribute("scripts", scripts);
Now in a JSP page, with JSTL, I do a normal forEach loop:
<c:if test="${not empty scripts}">
<c:forEach var="script" items="${scripts}" >
<script type="text/javascript"
src="${script}">
</script>
</c:forEach>
</c:if>
When loading the page, this results in:
<script type="text/javascript"
src="[/InfoKiosk/resources/scripts/jquery.cycle2.center.js">
</script>
<script type="text/javascript"
src=" /InfoKiosk/resources/scripts/jquery.cycle2.js">
</script>
<script type="text/javascript"
src=" /InfoKiosk/resources/scripts/slideshow.js]">
</script>
Notice the square brackets ([ and ]) that appear before the first script source and after the last. Where do they come from?
For some reason it is calling toString() on your set. This then turns your set into [script1, script2, script3], calling foreach on this string splits on the comma, creating the effect we see.
I could see exactly what you were seeing when I replace
request.setAttribute("scripts", scripts);
with
request.setAttribute("scripts", scripts.toString());
I could not reproduce what you were seeing without this, however I was running java 6.
Not an answer, but a helpful insight I hope!
The problem occured because the scripts variable was set in a JSP through an attribute for a custom tag, like this:
<t:genericpage scripts="${scripts}">
....
Of course, this converted the collection to a string by calling its toString() method. We have solved it in a different way, by setting the request attribute in the servlet.

How do I pass JavaScript values to Scriptlet in JSP?

Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.
simple, you can't!
JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.
This is for other people landing here.
First of all you need a servlet. I used a #POST request.
Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp:
You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() {
var sendVar = "hello";
$('#domId').click(function (e)
{
$.ajax({
type: "post",
url: "/", //or whatever your url is
data: "var=" + sendVar ,
success: function(){
console.log("success: " + sendVar );
<%
String received= request.getParameter("var");
if(received == null || received.isEmpty()){
received = "some default value";
}
MyJavaClass.processJSvar(received);
%>;
}
});
});
});
The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp">
<input type="hidden" name="inputName" value=""/>
<%
String pg = request.getParameter("inputName");
if(pg == null || pg.isEmpty()){
pg = "some default value";
}
DatasyncMain.changeToPage(pg);
%>;
</form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).
I Used a combination of the scriptlet, declaration, and expression tags...
<%!
public String st;
%>
<%
st= "<html> <script> document.writeln('abc') </script> </html>";
%>
<%=
" a " + st + " <br> "
%>
The above code is working completely fine in my case.

Reading a JSP variable from JavaScript

How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.

Categories