Accessing java variable from javascript on same jsp - java

Is it possible to access a String type variable defined in jsp from a javascript on the same page?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">
foo();
function foo()
{
var value = "<%=myVar%>";
alert(value);
}
</script>
</head>
<body>
<%
String myVar="blabla";
%>
</body>
</html>
In eclipse I am getting an error
myVar cannot be resolved to a variable

This won't work since you're trying to use an undefined variable. The code is generated like this:
... = myVar;
//...
String myVar = "blabla";
Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):
<%
String myVar="blabla";
%>
<script type="text/javascript">
foo();
function foo() {
var value = "<%=myVar%>";
alert(value);
}
</script>
Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:
<c:set name="myVar" value="blabla" />
<script type="text/javascript">
foo();
function foo() {
var value = "${myVar}";
alert(value);
}
</script>
If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:
var value = "<c:out value='${myVar}' />";
More info:
How to avoid Java code in JSP files?

Related

How to pass java string variable to the javascript function by jsp expression tag?

I want to passing a java String variable to the javascript function parameter using jsp expression tag.Below is my jsp page.
First.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function stringGenerate(str){
var x = document.getElementsByTagName("input");
x[0].value = str;
}
function numberGenerate(num){
var x = document.getElementsByTagName("input");
x[1].value = num;
}
</script>
</head>
<body>
<%
String num ="1234567890";
String str = "abcdefghij";
%>
<input type="text" name="string" readonly="readonly"/>
<input type="text" name="number" readonly="readonly"/><br/><br/>
<input type="button" value="String Generate" onclick= "stringGenerate(<%=str %>)" />
<input type="button" value="Number Generate" onclick= "numberGenerate(<%=num %>)" />
</body>
</html>
When I click on the button with value "Number Generate",then the num variable value(1234567890) will display on the textbox(name="number") but when I click on the button with value "String Generate",then there is nothing display on the corresponding text box(name="string").Here both num and str are string type varible but why only num variable value is displayed on textbox and why not str variable value is displayed?
Try using single quote ' when using string in HTML:
onclick= "stringGenerate('<%=str %>')"
^ ^
Full Code:
<input type="button" value="String Generate" onclick= "stringGenerate('<%=str %>')" />
The reason is that when the page is rendered by the browser, it puts the str and num values directly in the code, so it looks like:
<input type="button" value="String Generate" onclick="stringGenerate(abcdefghij)"/>
The browser basically thinks you're trying to reference a Javascript variable called 'abcdefghij'.
You should add the ' chars before and after your string text to let javascript know it should use the value of that text and not search for a variable with that name.
The declaration of str should look like this to make it work:
String str = "\'abcdefghij\'";
Please note, you can't use \" to escape as this would break your code.

jsp: how to get value from session?

I get an String array from session and I want to show the String from the array.
I know javascript can't get data from session directly. Is there any method I can get the data from session and transfer it to javascrip?
My code as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String[] sele = (String[])session.getAttribute("selections");%>;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Check List</title>
<script language="javascript" type="text/JavaScript" src="cookie.js">
</script>
<script text="text/javascript">
{
var selections = //String array form session
for(var v=0;v<selections.length;v++){
fillForm(selections[v]);
}
}
function fillForm(name){
var checkbox= document.createElement("input");
checkbox.type="checkbox";
checkbox.name=name;
checkbox.value=name;
checkbox.id=name;
var label = document.createElement("label");
label.htmlFor="id";
label.appendChild(document.createTextNode(name));
var container = document.getElementById("checklist");
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement("br"));
}
function submitAction(){
addUserName(document.getElementById("checklist"));
var elem = document.getElementById("checklist").elements;
for(i =0;i<elem.length;i++){
elem[i].checked = true;
}
var form = document.getElementById("checklist");
form.submit();
}
</script>
</head>
<body>
<form id="checklist" action="selection">
</form>
<Button type="button" onclick="submitAction()" name="submit">Submit</button>
</body>
</html>
Simply use JSP Expression Language and JSP JSTL
<script>
alert("value: ${selections}");
</script>
Here selections is an attribute that is set in any scope page, request, session or application.
You can directly access an attribute form session scope:
{sessionScope.selections}
Note: I don't know that Java ArrayList does work in JavaScript as well. If it doesn't work then simply set a comma separated string as session attribute and split it in JavaScript as shown below.
Sample code:
<script>
var selections = "${sessionScope.csv}".split(",");
for ( var v = 0; v < selections.length; v++) {
alert(selections[v]);
}
</script>
Here csv is a comma separated string value that is set in session scope.
Use JSP JSTL and EL instead of Scriplet that is more easy to use and less error prone.
You can achieve it in JSTL without using JavaScript. Simply iterate the list using <c:forEach> tag and add that much of check boxes and labels.
Sample code:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<body>
...
<c:forEach items="${selections }" var="name">
<input type="checkbox" name="${name}" value="${name}" id="${name}">
...
</c:forEach>
</body>

How to use jsp variable in javascript array?

Hi I have a jsp page where I have some variable. I want to access the variable in a javascript array. How can I get this?
Demo.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
int i=1;
int j=2;
int k=3;
int l=4;
%>
</body>
</html>
I want to use these 4 variables in the javascript array and print them.
How can I achieve this?
Try,
<script language="JavaScript">
var Arr = new Array();
Arr[0] = '<%=i %>';
Arr[1] = '<%=j %>';
Arr[2] = '<%=k %>';
Arr[3] = '<%=l %>';
</script>
In Java script you have to use scriplet tag to use jsp data.
<%
Integet a = i ; //here i is your jsp variable
%>
In order to make this work you should declare the variable before using it (as always):
<%
String myVar="blabla";
%>
<script type="text/javascript">
foo();
function foo() {
var value = "<%=myVar%>";
alert(value);
}
</script>
Or :
var result = [];
result.push(<%i%>);
result.push(<%j%>);
result.push(<%k%>);
result.push(<%l%>);
You can access it using JSTL.
set java variable to JSTL variable
Access it in Java script as
var x='${jstl_varialbe_goes_here
}';
alert(x);

passing the value of an array to a method in javascript

I have to create an HTML table in which I will have images to display. further I want to pass this path to the next servlet page. for this I have created a separate method in javascript. Now the problem is this, whenever I click on any image it passes the same path everytime. please give me any solutions for this problem or tell me any alternate of passing the path to next page.
my code is--->
<%#page import = "java.util.*" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link href="Style.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<center>
<h3>${requestScope.payment}</h3>
<jsp:include page="Header.jsp"/>
<jsp:include page="Menu2.jsp"></jsp:include>
<form method="post" action="ProductFeatures" id="myform">
<table border="1" bordercolor="green" bgcolor="yellow" align="center" id="store" >
</table>
</form>
<%
ArrayList<String> l = null;
if(request.getAttribute("list") instanceof ArrayList<?>){
l = (ArrayList<String>)request.getAttribute("list");
}
%>
<script type="text/javascript">
window.onload = function(){
var path = new Array();
var imagepath = new Array();
var table = document.getElementById("store");
var j=0;
var k=0;
var row = null;
<%for(int i=0;i<l.size();i++) {%>
path.push("<%=l.get(i)%>");
<%}%>
for(i=0;i<path.length;i++){
imagepath[i] =path[i].replace ("F:java_projectsApplication4images","F:\\java_projects\\Application4\\images\\");
}
for(i=0;i<path.length;i++){
if(i%4==0){
row = table.insertRow(j);
k=0;
j++;
}
var data = imagepath[i];
var cell = row.insertCell(k);
var image = document.createElement("img");
image.setAttribute("src",imagepath[i]);
image.setAttribute("height","160");
image.setAttribute("width","120");
image.setAttribute("onclick",function(){getDetails(data);});
cell.appendChild(image);
row.appendChild(cell);
k++;
}
};
function getDetails(imagepath){
document.write(imagepath);
if(path.length>10){
var form = document.getElementById("myform");
var input = document.createElement("input");
input.type="hidden";
input.value=imagepath;
input.name="imagepath";
form.appendChild(input);
form.submit();
}
}
</script>
<jsp:include page="Footer.jsp"/>
</center>
</body>
</html>
Here in this code in function getDetails variable imagepath always contains the same value. please somebody tell me wheres the bug in this code. I am not getting it properly.
Change the following line:
image.setAttribute("onclick",function(){getDetails(data);});
into:
image.setAttribute("onclick",(function(d){return function(){getDetails(d);}}(data));
Also, the line:
row.appendChild(cell);
is redondant because the cell was inserted with row.insertCell(k)

Why isn't JSP out.print() function working properly

I've been working with a JSP+Java+Html, and I've encountered a problem with out.print() function, in a for cycle.
My function getGeneAvailableTaxonomies() returns a list of integer numbers (of type List<Integer>), and I want to print these numbers in an interface.
Here's my code:
for(Integer i : ApplicationExtender.getApplicationExtender(application).getGeneAvailableTaxonomies())
{
out.print(String.format("<option value=\"%1$d\">%2$s</option>", i, TaxonId.getOrganismFromId(i)));
}
The doce %1$d should stand for the i integer value, while %2$s should stand for the other parameter, the taxonomy id value as String.
But, unfortunately, this is what appears:
While I would like to see something like:
There's surely an error on my out.print() function call... but what's wrong?
Many thanks
You dont need the "$" in your format String. As you may know, using scriptlets is not a good way to do Java Web Development. I think that using JSTL is far better, as you won't mix Java code with markup in your JSP's.
Edit: The printf method is not present in out object as I said earlier, since it is a JspWriter and JspWriter not inherit from PrintWriter (that have printf). Sorry. So, try this (it worked for me).
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<select>
<%
String[] strings = new String[]{ "aaa", "bbb", "ccc", "ddd" };
for ( int i = 0; i < strings.length; i++ ) {
out.print( String.format( "<option value='%d'>%s</option>", i, strings[i] ) );
}
%>
</select>
</body>
</html>
If you want to use a PrintWriter as in Servlets, so this will work:
<%#page import="java.io.PrintWriter"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<select>
<%
PrintWriter writer = new PrintWriter( out );
String[] strings = new String[]{ "aaa", "bbb", "ccc", "ddd" };
for ( int i = 0; i < strings.length; i++ ) {
writer.printf( "<option value='%d'>%s</option>", i, strings[i] );
}
%>
</select>
</body>
</html>
Your print/format code seems OK when I run it on http://ideone.com/u8fDT. You probably just need to have the JSP recompiled (should probably happen automatically but may sometimes require server restart).
Also, mixing HTML and Java code like this is a pretty painful way to work. JSTL or a templating system like FreeMarker would make your life easier.
try this as much i have understood :
String option = "<option value=\""+d+"\">"+s+"</option>";
out.print(option);
using String.format
out.print(String.format("<option value=\"%d\">%s</option>", i, TaxonId.getOrganismFromId(i)));
Updated
as you have mentioned in comments that TaxonID.getOrganismFromId(i) is returning int so the there is only one change in your original code %2$s to %2$d thats it...
out.print(String.format("<option value=\"%1$d\">%2$d</option>", i, TaxonId.getOrganismFromId(i)));

Categories