I attempted to convert java array to js array. but it gives error as "k cannot be resolved to a variable".x.getrows returns array.
<% MySQLAccess x=new MySQLAccess();%>
<% String b[]=x.getRows();%>
var message="<%out.print(b[0]);%>"
console.log(message)
var data=new Array();
<% for(int k=0;k<b.length ;k++) %>
<% {%>
var temp=<%= b[k] %>
data[<% =k %>]=temp;
<%}%>
#user2815407 What you are receiving in your string array? May be something like [str1,str2,str3]. If so you can easily convert this string array into js array.
var values = [];
values = //Your_string_array
//Iterate through each value
$.each(values, function( index, value ) {
console.log(value);
});
See this fiddle. This may not be optimal way to convert java to js array. Hope this will give you some idea. Let me know if this helps.
I advice not to use scriplets, but here's the solution to your problem :
<% String b[] = new String[]{"10", "20", "30"};%>
var message = "<%out.print(b[0]);%>"
console.log(message)
var data = new Array();
<% for(int k=0;k<b.length;k++){%>
var temp =<%=b[k]%>
data[<%=k%>] = temp;
<%}%>
The error was just un-necessary spaces.
My advice to fix this code: forget about it:
you should NEVER use scriptlets in JSPs
JS string literals need quotes around them, and escaped quotes and other escaped special chars inside
JSON is the tool you should use.
So, in your controller, use
request.setAttribute("jsArray", someJsonSerializer.toJson(javaArray));
And in your JSP:
var data = ${jsArray};
Related
I am parsing the html from the following webpage using Jsoup. How do I get the value from the variable price_ourBase:
<script type="text/javascript">
var price_ourBase = 279;
.
.
.
</script>
JS:
Element upperContainer_inner = document.select("div.upperContainer_inner").first();
Element table = upperContainer_inner.select("table.645.0.left.0.0").first();
Element script = table.select("script").first();
Element base_ourPrice = script.select("base_ourPrice").first();
price = (?, not sure what to put here or if there is more code needed).text();
I dont think jSoup can parse javascript like that. But, you could select the contents of the script with jSoup and then you could do something like
String[] result = script.toString().split(" ");
if(result[1].equals("price_ourBase"))
System.out.println("Our price is "+result[3].split(";")[0]);
I have achieved sending an integer variable to a jsp page using the following code:
resp.sendRedirect(("result.jsp?fibNum=" + fibNum));
But when I try the same to pass the array, int[] fibSequence I get the following passed to the address bar of the jsp page:
Does anyone have any advice on how I can output the array value passed over to the jsp page?`
This is how I sent the array across to the result jsp page within the doPost():
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
// read form fields
String fibNum = req.getParameter("fibNum");
try{
//Get reference from server's registry
Registry registry = LocateRegistry.getRegistry("127.0.0.1");
//Lookup server object from server's registry
IFibonacci fibonacci_proxy = (IFibonacci)registry.lookup("PowerObject");
int fibMax = Integer.parseInt(fibNum);
//Invoke server object's methods
//Get Fibonacci array.
int[] fibSequence = fibonacci_proxy.fibonacciArrayTest(fibMax);
for (int value : fibSequence) {
System.out.println(value);
}
//System.out.println(Arrays.toString(fibSequence));
}catch(NotBoundException nbe){
nbe.printStackTrace();
}catch(RemoteException re){
re.printStackTrace();
}
//send input to the result page using a redirect
//resp.sendRedirect(("result.jsp?fibNum=" + fibNum));
resp.sendRedirect(("result.jsp?fibSequence=" + fibSequence));
}
How I've tried to retrieve the array values on the jsp page and print them, but I'm getting a fibSequence cannot be resolved to a variable although this is the name of the array passed over:
Return to Main<br>
<%String[] var_array=request.getParameterValues("fibSequence");%>
<%System.out.print(""+fibSequence);%>
</form>
Trust the compiler. fiBSeq ist not defined. You defined fibSequence. But passing that array as an argument will not work, because you will pass (int[]).toString() which is probably not what you want. You can serialize and encode it, if it is not too big. Or post it.
EDIT 1
int [] array = {1,2,3,4,5,6,7,8,9};
System.out.print(""+array);//<-- print [I#15db9742 or similar
EDIT 2
Encoding the array on the sender side
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
String param = Arrays.toString(array);
param = param.substring(1, param.length()-1);//removing enclosing []
String encArray = URLEncoder.encode(param, "utf-8");
// Send encArray as parameter.
resp.sendRedirect(("result.jsp?fibSequence=" + encArray));
Decoding the array on the receiver side
String encArray = request.getParameterValues("fibSequence");
String decArray = URLDecoder.decode(encArray,"utf-8");
//Now you can parse the list into an Integer list
String [] var_array = decArray.split(",");
In jsp, put the code between <% ... %>. If you get some unresolved symbol errors you have to import the missing libraries.
Can be one or more of the following, simply copy the statements at the top of the page.
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%# page import="java.util.*" %>
(maybe java.util is imported per default, I am not sure)
BUT ATTENTION
Be aware of not sending too much data in this manner! The size of an URL maybe is not unlimited. Also the data is visible in the URL, a 'nasty' user could simply copy and reproduce requests.
A better way to send data is using HTTP post.
Here is the better answer to transfer array variable from servlet to jsp page:
In Servelet:
String arr[] = {"array1","array2"};
request.setAttribute("arr",arr);
RequestDispatcher dispatcher = request.getRequestDispatcher("yourpage.jsp");
dispatcher.forward(request,response);
In Jsp:
<% String str[] = (String[]) request.getAttribute("arr"); %>
<%= str[0]+""+str[1] %>
Im trying to pass a Collection of items converted into String with JsonArray to my Javascript but dont work.
This is the code of the class
InformeAmenazasAGR = manager.preparaInformeRiesgoActivos(idDimension, tipoActivo, idActivo, tipoActivoTexto, nombreActivo, recursos);
JSONArray JSonArray = new JSONArray();
JSonArray.put(InformeAmenazasAGR);
String texto = JSonArray.toString();
//Delete the first and last char.
texto = texto.substring(1, texto.length()-1);
request.setAttribute("InformeAmenazasAGR", texto);
return mapping.findForward( "informeActivosAGR" );
This returns one String like this:
[
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
My JSP with Javascript (im using ExtJS and follow I tried Passing a Java string to Javascript post but dont work)
var DatosAmenazas = new String("<%request.getAttribute("InformeAmenazasAGR");%>");
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: DatosAmenazas
});
What am i doing wrong?
Thank you in advance
EDIT: If i put the raw String that i save in request.setAttribute("InformeAmenazasAGR", texto); it works:
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: [
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
});
I think using the Java scriptlet inside javascript is not good practice,
instead you can use the $(InformeAmenazasAGR) to set the request attribute value to a hidden element and put the hidden element anywhere inside your html <body> like this,
<input type="hidden" id="jsonData" value="${InformeAmenazasAGR}">
then, get the hidden element value like,
var DatosAmenazas = new String($('#jsonData').val());
if you need the request attribute InformeAmenazasAGR to be converted into json data then instead of above you can change your above line as,
var DatosAmenazas = JSON.parse($('#jsonData').val());
FYI: Java scriptlets run on server side while javascript on client side
I want to retrieve a value of a javascript section in a PHP file with my application in Java.
The PHP page contain something like :
<script type="text/javascript">
var tab= new Array();
tab[0] = "value0";
tab[1] = "value1";
tab[2] = "value2";
</script>
I'm using jsoup for parsing the HTML tag. I tried to use Rhino but I don't find example.
Context context = Context.enter();
Scriptable scope = context.initStandardObjects();
Object result = null;
Reader reader = new InputStreamReader(inputStreamOfThePage);
result = context.evaluateReader(scope, reader, "page", 1 , null );
Scriptable varValue = (Scriptable)scope.get("tab", scope);
String valueStr = (String)varValue .get("tab[0]", varValue );
It's giving me the exception :
java.lang.ClassCastException: org.mozilla.javascript.UniqueTag cannot be cast to org.mozilla.javascript.Scriptable
I don't know how to cast the object. Maybe there is a better way to do what I want.
Thanks
Jsoup is not suitable to parse Javascript... It's normal it doesn't work !
I have the following code in javascript:
<script type="text/javascript"
src="#{facesContext.externalContext.requestContextPath}/js/sample-points.js"></script>
<script type="text/javascript">//<![CDATA[
var cloudmade = new CM.Tiles.CloudMade.Web({key: 'bbb'});
var map = new CM.Map('cm-example', cloudmade);
map.setCenter(new CM.LatLng(51.50874, 22.76367), 4);
var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}
var clusterer = new CM.MarkerClusterer(map, {clusterRadius: 70});
clusterer.addMarkers(markers);
//]]></script>
"samplePoints" is an array of coordinates which I can use to show markers on the map.
Map is showing here:
<div id="cm-example" style="width: 99.5%; height: 600px"></div>
How can I provide this array from jsf/richfaces without using file (e.g. I want to fetch those data from db, create array and send to this script)?
Thanks
Just let JSF print it as if it is JavaScript code.
Replace
var markers = [];
for (var i = 0; i < samplePoints.length; i++) {
markers.push(new CM.Marker(new CM.LatLng(samplePoints[i][0], samplePoints[i][1])));
}
by (assuming Facelets)
var markers = [];
<ui:repeat value="#{bean.samplePoints}" var="samplePoint">
markers.push(new CM.Marker(new CM.LatLng(#{samplePoint[0]}, #{samplePoint[1]})));
</ui:repeat>
where #{bean.samplePoints} returns a List<BigDecimal[]> or something.
See this Link
using jsFunction you can load any data structure (e.g. Points), and on your clients side you get a javaScript data structure that you can easily access it (point.x).