I have a controller class in Spring MVC, where i am returning a HaspMap as Model attribute -
#ModelAttribute("regPrefix")
public Map<String, String> getRegPrefixesOfDepartmentforGroup(final Model model, final HttpServletRequest request) {
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, regPrefix);
return regPrefixOfDept;
}
Now in the corresponding JSP page, i am trying to access the Hashmap and store the key/value pairs of the Hasmap in a variable using JavaScript. I am trying like below but its not right. Can anyone suggest how to do that
<script>
$("#deptIdSelection").change(function()
{
var obj = document.getElementById("deptIdSelection");
var textItem = obj.options[obj.selectedIndex].text;
alert(textItem);
var mapObj = "${regPrefix}";
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
}
);
</script>
Try to access map values like this:
${regPrefix.key}
If you want to iterate through the map keys, it is not so easy: JSTL is executed on the server side and is rendered to a plain text - no JavaScript objects are created. The following line var mapObj = "${regPrefix}"; will be rendered to a string representation of HashMap, not to a JavaScript object.
To convert your map to a JavaScript object I suggest you to use one of the following methods:
1) Convert your map to JSON and pass it as a String. So when it is rendered to a JavaScript code, it will look like a regular JS object: var mapObj = {"key": "value", ...};. You can use Gson or any other JSON library to achieve this:
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, new Gson().toJson(regPrefixOfDept));
And then var mapObj = ${regPrefix}; (note that you need no quotes around because you want mapObj to be a JS object, not a string)
2) Iterate through your map using <c:forEach> to generate a JS object:
var mapObj = {
<c:forEach items="${regPrefix}" var="item" varStatus="loop">
${item.key}: '${item.value}' ${not loop.last ? ',' : ''}
</c:forEach>
};
In both cases you should be able to then call
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
Related
I'm trying to call a function with Frida that takes a string array as one of its arguments.
public void coolFunction(long value, String[] strArr);
Within Java it gets called like this:
long importantValue = 4L;
String[] importantArr = new String[]{"TEST"};
coolFunction(importantValue, importantArr);
The overload looks like this: .overload('long', '[Ljava.lang.String;')
I could probably create a string array from scratch, but I don't know how to express it in Javascript. What's the Frida equivalent of new String[]{"TEST"}?
Because of that I tried to turn an ArrayList<String> into a String[], which also wasn't successful.
As far as I can tell there are two simple ways to turn ArrayList<String> into String[]:
Attempt #1:
List<String> list = new ArrayList<String>();
list.add("TEST");
String[] stringArray = list.toArray(new String[0]);
If I try to express it with Javascript it looks like this:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var stringArray = arrList.toArray(Java.use("[Ljava.lang.String;").$new(0));
This fails with the following error message:
Error: no supported overloads
Attempt #2:
List<String> list = new ArrayList<String>();
list.add("TEST");
Object[] objectArray = list.toArray();
String[] stringArray = (String[]) objectArray;
Javascript:
var AL_class = Java.use("java.util.ArrayList");
var arrList = AL_class.$new();
arrList.add("TEST");
var arrayButAsObject = arrList.toArray();
var stringArray = Java.cast(arrayButAsObject, "[Ljava.lang.String;");
This fails because it assumes that I want to use Javascript's toArray() function.
The solution to this problem is probably very simple but I've been stuck here for quite a while now and can't seem to figure it out. Any help would be appreciated.
Instead of trying to construct a java.util.List and then convert it to an array I would use the Frida function Java.array and directly construct a Java String array:
var javaStringArray = Java.array('java.lang.String', [ "Test" ]);
How can I get each attribute within a Json String?
I got the Json by converting first my array of objects in JavaScript via JSON.stringify. Afterwards I used ajax to pass the string to my servlet.
Servlet Code:
String data = request.getParameter("jsonData");
System.out.println("json data: " + data);
Result:
[{"courseID":"1","codePI":"PO-BSINSYS-02.01","curriculumID":"3"},
{"courseID":"2","codePI":"PO-BSINSYS-02.02","curriculumID":"3"}]
What I want is to get the individual values of the json so that I can assign them later to my object.
E.g.
ArrayList<Curriculum> arrCur = new ArrayList<>();
for (int x = 0; x < array.size(); x++) {
Curriculum cur = new Curriculum();
cur.setCourseID(courseID[x]);
cur.setCodePO(codePI[x]);
cur.setCurriculumID(curriculumID[x]);
arrCur.add(cur);
}
As "crowder" mentioned, you need to parse the json.
There are several ways to do it.
low-level libraries that would convert your string into a
JSONObject which is sort of a map (with keys "courseID", "codePO"
etc). At the time I used fasterxml but I see a newer approach here:
http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
Higher-level libraries that would map the json directly into
Java business Objects such as "Curriculum". My own experience was
focused on replacing the simple Servlet with Spring - see for
example https://spring.io/guides/gs/rest-service/
good luck
You can use this way if you are sending arry of object from javascript and if you class -
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
}
Use like this -
String data = request.getParameter("jsonData");
JSONArray jsonArray = new JSONArray(data);
java.lang.reflect.Type curriculumType =new com.google.gson.reflect.TypeToken<List<Curriculum>>(){}.getType();
List<Curriculum> curriculum = new GsonBuilder().create().fromJson(jsonArray.toString(), curriculumType);
This will assign list of Curriculum. Hope this will help you.
You can also use jackson-databind API to convert your json to java object.
Create your bean for Curriculum.
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
public Integer getCourseID() {
return courseID;
}
public void setCourseID(Integer courseID) {
this.courseID = courseID;
}
public String getCodePI() {
return codePI;
}
public void setCodePI(String codePI) {
this.codePI = codePI;
}
public Integer getCurriculumID() {
return curriculumID;
}
public void setCurriculumID(Integer curriculumID) {
this.curriculumID = curriculumID;
}
}
Following is the code to convert your json to Curriculum object
JSONArray jsonArray = getJSONArray();
ObjectMapper objectMapper = new ObjectMapper();
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
//convert json string to object
try {
Curriculum curr= objectMapper.readValue(jsonData.toString().getBytes(), Curriculum.class);
System.out.println(curr);
} catch (Exception e) {
e.printStackTrace();
}
}
I am at a point where I can pull a single javascript declaration such as:
var cars = ["Saab", "Volvo", "BMW"];
parsed from a page.
I would like to be able to get all the elements of the array ("Saab", "Volvo", "BMW") from this declaration.
Should I be using some javascript engine for this, or what else would be the best way to get javascript variable values from my Java code.
I would hate to reinvent the wheel if something is already out there that is able to do this, so I am just looking for advice on something I can use to do this function.
I assume you found a way to transport that javascript object/array into your Java domain as a String or Stream. What you want now is a JSON parser.
One way is to use json.org or other libraries. Further information about json parsing can be found in this thread:
How to parse JSON in Java
The [org.json][1] library is easy to use. Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
} You may find extra examples from: [Parse JSON in Java][2]
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
[1]: http://www.json.org/java/index.html
[2]: http://theoryapp.com/parse-json-in-java/
You might also want to look into jsonb (https://jcp.org/en/jsr/detail?id=353) that was introduced with Java 7. You can bind an object model and transform JSON objects into java objects and vice versa.
you can iterate through all the values in 'window'
for ( var key in window )
{
if ( typeof window]key] == 'object' && window]key].length > 0 )
{
//this is the array you are looking for
}
}
You can get access to javascript object from java by using httpunit
Method 1: JSON parser, as Alex's answer.
Method 2: Javascript parser for Java
Method 3: Regular Expression (A weird way I figured out!)
First pattern is var\s+([a-zA-Z0-9]+)\s+=\s+\[(.*)\]\s*;*
var + one or more space(s) + variable name($1) + one or more space(s) + equals sign + one or more space(s) + array content($2) + ......
Second pattern is "(.*?)", get the string between two quotation marks.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSParser {
public String arrayName;
private String tempValues;
public ArrayList<String> values = new ArrayList<String>();
public boolean parseJSArray(String arrayStr){
String p1 = "var\\s+([a-zA-Z0-9]+)\\s+=\\s+\\[(.*)\\]\\s*;*";
Pattern pattern1 = Pattern.compile(p1);
Matcher matcher = pattern1.matcher(arrayStr);
if(matcher.find()){
arrayName = matcher.group(1);
tempValues = matcher.group(2);
Pattern getVal = Pattern.compile("\"(.*?)\"");
Matcher valMatcher = getVal.matcher(tempValues);
while (valMatcher.find()) { // find next match
String value = valMatcher.group(1);
values.add(value);
}
return true;
}else{
return false;
}
}
}
With JDK 8 the code bellow works :
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String js = "var carsfromjs = [\"Saab\", \"Volvo\", \"BMW\"]";
engine.eval(js);
String[] cars = (String[])engine.eval("Java.to(carsfromjs, \"java.lang.String[]\")");
for(int i=0; i<cars.length; i++){
System.out.println(cars[i]);
}
You can find many ways to access Javascript code throught "nashorn" :
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/
I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?
Controller:
List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;
View:
var fruitList = '#ViewBag.FruitList';
When I run the program fruitList comes back as System.Collections.Generic.List 1[System.String]
Way 1:
You can use Html.Raw() and Json.Encode for it:
var fruitList = #Html.Raw(Json.Encode(ViewBag.FruitList));
Way 2:
you can use Json.Parse() in combination with Html.Raw() to parse the raw string in to json:
var fruitList = JSON.parse('#Html.Raw(ViewBag.FruitList)');
Way 3:
you can also use JsonConvert class using NewtonSoft JSON to serialize it to json:
var fruitList = '#JsonConvert.Serialize(ViewBag.FruitList)';
If I have a Salesforce custom list setting, 'Info_List__c' with 1 field, 'Info_Field__c'.
What would a method look like that would iterate through the list and return all entries.
And how would I call that method from a VF page and store the results in a JS object?
In controller
global with sharing class Ctrl{
#RemoteAction
global static List<String> getList(){
List<String> result = new List<String>();
List<Info_List__c> lst = [Select Info_Field__c from Info_List__c];
for(Info_List__c lstObj : lst){
result.add(lstObj.Info_Field__c);
}
return result;
}
}
And in JS side
var strArr = Ctrl.getList();
If you have namespace it would be (e.g. NS)
var strArr = NS.Ctrl.getList();