Reading a JSP variable from JavaScript - java

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.

Related

DOUBLE_WHITESPACE in PATH error

i am learning JSTL and from tutorials point in this link
when i tried to execute that example in the page which is
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:url> Tag Example</title>
</head>
<body>
TEST
</body>
</html>
i am getting following error.
but i could not understand why and what is the solution for that?
The validator is probably confused by the nested double quotes:
TEST
You can make the code cleaner by doing:
<c:url value="/jsp/index.htm" var="myUrl" />
TEST
which assigns the value of the processed URL to a var named 'myUrl' and then uses JSP Expression language to output the URL.
Change this line:
<title><c:url> Tag Example</title>
By:
<title>&LT;c:url&GT; Tag Example</title>
Otherwise, the JSP engine will interpret this (<c:url>) as the beginning of a tag to be processed.
You need to escape your nested quotes as
TEST
Otherwise the HTML parser perceives "<c:url value=" as the href value and complains about the space in between. Alternatively, you can make use of single and double quotes as
<a href='<c:url value="/jsp/index.htm"/>'>TEST</a>
Or,
TEST

Pass selected value from dropdown using JSP

I need to implement some basic dropdown using jsp and java, but I can't find more info how to do that. So I never write something using JSP and when I didnt find nothing that help the last options for me was to ask.
I want to get the selected value and when click the button to send the value to anoher .jsp file ("selector.jsp in my case")
Please folks help me with some easy solution.
p.P.: Sorry for my english (:
index.jsp
<FORM method="post" action="selector.jsp">
<select name="select" id="dropdown">
<%
Test t = new Test();
t.getList().add("a");
t.getList().add("b");
t.getList().add("c");
for(int i=0; i < t.getList().size(); i++){
%>
<Option value="<%t.getList().get(i);%>"><%=t.getList().get(i)%></Option>
<%}%>
</select>
<input type="submit" value="click">
selector.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
You selected:
<%
request.getParameter("select");
request.getParameterValues("select");
%>
</body>
</html>
I found a solution by removing
value="<%t.getList().get(i);%>"
from and leave the code just with
<Option><%=t.getList().get(i)%></Option>
but i don't know why... if someone can explain will be great.
Thx! (:
As you have indicated in your post, the problem is solved by replacing
value="<%t.getList().get(i);%>"
with
<Option><%=t.getList().get(i)%></Option>
The reason that works is as follows:
In your first form, <%t.getList().get(i);%>, you have a JSP scriptlet. This is Java code that is executed inline. In your case, this executes the "get" method. Note however that the get method returns a value, but this value is not output into the response stream.
In your second form, you have formed a JSP expression by using "<%=". "<%=" is shorthand for "out.println", thus you have provided shorthand for the following:
<Option><% out.println(t.getList().get(i)) %></Option>
This writes the return value of the method call to the output stream. So that when this output reaches the browser, there is an actual value within the Option tags.

How to parse a webpage that includes Javascript? [duplicate]

This question already has answers here:
Parse JavaScript with jsoup
(2 answers)
Closed 9 years ago.
I've got a webpage that creates a table using Javascript. Right now I'm using JSoup in my Java project to parse the webpage. By the way JSoup isn't able to run Javascript so the table isn't generated and the source of the webpage is incomplete.
How can I include the HTML code created by that script in order to parse its content using JSoup? Can you provide a simple example? Thank you!
Webpage example:
<!doctype html>
<html>
<head>
<title>A blank HTML5 page</title>
<meta charset="utf-8" />
</head>
<body>
<script>
var table = document.createElement("table");
var tr = document.createElement("tr");
table.appendChild(tr);
document.body.appendChild(table);
</script>
<p>First paragraph</p>
</body>
</html>
The output should be:
<!DOCTYPE html>
<html>
<head>
<title>
A blank HTML5 page
</title>
<meta charset="utf-8"></meta>
</head>
<body>
<script>
var table = document.createElement("table");
var tr = document.createElement("tr");
table.appendChild(tr);
document.body.appendChild(table);
</script>
<table>
<tr></tr>
</table>
<p>
First paragraph
</p>
</body>
</html>
By the way, JSoup doesn't include the table tag as it isn't able to execute Javascript. How can I achieve this?
First possibility
You have some options outside Jsoup, i.e. employing a "real" browser and interact with it. An excellent choice for this would be selenium webdriver. With selenium you can use different browsers as back end, and maybe in your case the very lightweight htmlUnit would do already. If more complicated JavaScript is called there is often no other choice then running a full browser. Luckily, phantomjs is out there and its footprint is not too bad (headless and all).
Second possibility
Another approach could be that you grab the javascript source with JSoup and start a JavaScript interpreter within Java. For that you could use Rhino. However, if you go that path you might as well use HtmlUnit directly, which is probably a bit less bulky.

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.

how to use jquery autocomplete?

i am creating a web project using JSP, and is trying to implement a simple search for users from my database using jquery autocomplete, however i am having trouble understanding how it works. i have little to no knowledge on jquery and ajax just to let you know. i have done the following code and am stuck.
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,ewa.sendEmail,ewa.pwGen,ewa.hashPw,java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="text" id="search" name="search"/>
<script>
$("#search").autocomplete("getdata.jsp");
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="ewa.dbConnect,java.sql.*" %>
<%! dbConnect db = new dbConnect(); %>
<%
String query = request.getParameter("q");
db.connect();
Statement stmt = db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT username FROM created_accounts WHERE username LIKE "+query);
while(rs.next())
{
out.println(rs.getString("username"));
}
db.disconnect
%>
if i am not wrong i read from a website, the parameter q is default and is just there, however how do i display the data? how do i pass the values from getdata.jsp into the autocomplete?
You're calling the autocomplete script tag before jQuery has been included. So, not having jQuery to latch onto (as the jQuery object hasn't been defined), nothing from the jQuery autocomplete plugin will load.
You have
<script src="js/jquery.autocomplete.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
It should be
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="js/jquery.autocomplete.js"></script>
Reverse the order, and the Firebug errors you mentioned should disappear; I'm not sure it'll solve everything, but nothing will work until that's resolved.
I don't see jQuery UI being included (that one provides the autocomplete functionality)
http://jqueryui.com/demos/autocomplete/
So you need to include jquery.ui.autocomplete.js
(Or are you using the plugin autocomplete? if so, move to the jquery UI version)
Could also be that the data from getdata.jsp is malformed for the use in autocomplete.
How you tried debugging the javascript in a browser such as chrome or in firefox(with firebug)
I usual give (for jquery UI autocomplete) a JSON formatted answer, while I see your answer loop give a CR delimited list.
In getdata.jsp instead of produce:
jim<cr>
jack>cr>
jhon<cr>
try to return:
[{label: 'jim', value: 'jim'}, {label:
'jack', value: 'jack'}, {label:
'jhon', value: 'jhon'}]

Categories