Replace equal with semicolon in Java Script Object - java

I am sending the Map<String,String> object from servlet to jsp whose key is attribute name and value jsonvalue. My Requirement is to collect the value of key in variable that is root here. But when I tried to assign these map object to JavaScript variable i'ts throwing an error because the map object contains the = operator in the data. So to remove the error I assigned = with : manually its working fine.
So please tell me how do I remove the = with : with JavaScript code? Or is there any way to send the data with semicolon from servlet?
The data is coming in this format:
var trees= {dage={"nodeId":3,"value":"0-7","children":[{"nodeId":2,"value":"4-7","children":[{"nodeId":1,"value":"6-7","children":[{"nodeId":0,"value":"7","children":[]},{"nodeId":4,"value":"6","children":[]}]},{"nodeId":6,"value":"4-5","children":[{"nodeId":5,"value":"5","children":[]},{"nodeId":7,"value":"4","children":[]}]}]},{"nodeId":10,"value":"0-3","children":[{"nodeId":9,"value":"2-3","children":[{"nodeId":8,"value":"3","children":[]},{"nodeId":11,"value":"2","children":[]}]},{"nodeId":13,"value":"0-1","children":[{"nodeId":12,"value":"1","children":[]},{"nodeId":14,"value":"0","children":[]}]}]}]},
dpob={"nodeId":6,"value":"4;3;5;6;1;2;0","children":[{"nodeId":5,"value":"0","children":[{"nodeId":4,"value":"0","children":[{"nodeId":3,"value":"0","children":[{"nodeId":2,"value":"0","children":[{"nodeId":1,"value":"0","children":[{"nodeId":0,"value":"0","children":[]}]}]}]}]}]},{"nodeId":12,"value":"4;3;5;6;1;2","children":[{"nodeId":11,"value":"3;5;6;1;2","children":[{"nodeId":10,"value":"5;6;1;2","children":[{"nodeId":9,"value":"2","children":[{"nodeId":8,"value":"2","children":[{"nodeId":7,"value":"2","children":[]}]}]},{"nodeId":15,"value":"5;6;1","children":[{"nodeId":14,"value":"1","children":[{"nodeId":13,"value":"1","children":[]}]},{"nodeId":17,"value":"5;6","children":[{"nodeId":16,"value":"6","children":[]},{"nodeId":18,"value":"5","children":[]}]}]}]},{"nodeId":22,"value":"3","children":[{"nodeId":21,"value":"3","children":[{"nodeId":20,"value":"3","children":[{"nodeId":19,"value":"3","children":[]}]}]}]}]},{"nodeId":27,"value":"4","children":[{"nodeId":26,"value":"4","children":[{"nodeId":25,"value":"4","children":[{"nodeId":24,"value":"4","children":[{"nodeId":23,"value":"4","children":[]}]}]}]}]}]}]}}
I am trying to iterate this map working fine if : is there to get the key.
for (var key in trees){
if(key===attribute_name){
root=trees[key];
break;
}
}
This is the jsp code through which i am getting the data
<script type="text/javascript">
var treeStructure=<%=request.getAttribute("treeData")%>;
<script>

Convert your Map<String, String> into a JSON string using a JSON parse library. Then, set this data into a variable in your JavaScript code (after parsing it properly).
Here's an example using Jackson library.
Java servlet (or whatever controller you use) code:
Map<String, String> yourMap = ...;
//fill your map...
request.setAttribute("theMapAsJSON", new ObjectMapper().writeValueAsString(yourMap));
JavaScript code:
<script type="text/javascript">
var treeStructure = JSON.parse('${theMapAsJSON}'); //naive approach
<script>

Related

Multiple inline insert using Ajax & JSP [duplicate]

I have a JSON object sent from the browser to the jsp page.How do I receive that object and process it in jsp.Do I need any specific parsers? I have used the following piece of code.But it wouldn't work.Essentially I should read the contents of the object and print them in the jsp.
<%#page language="java" import="jso.JSONObject"%>
<%
JSONObject inp=request.getParameter("param1");
%>
<% for(int i=0;i<inp.size();i++)
{%>
<%=inp.getString(i)%>
<%
}
%>
My preferred solution to this problem involves using a JSON parser that provides an output that implements the java.util.Map and java.util.List interface. This allows for simple parsing of the JSON structure in the JSP Expression language.
Here is an example using JSON4J provided with Apache Wink. The sample imports JSON data from a URL, parses it in a java scriptlet and browses the resulting structure.
<c:import var="dataJson" url="http://localhost/request.json"/>
<%
String json = (String)pageContext.getAttribute("dataJson");
pageContext.setAttribute("parsedJSON", org.apache.commons.json.JSON.parse(json));
%>
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
To make this clean, it would be preferable to create a JSTL tag to do the parsing and avoid java scriplet.
<c:import var="dataJson" url="http://localhost/request.json"/>
<json:parse json="${dataJson}" var="parsedJSON" />
Fetch the name of the node at index 1 : ${parsedJSON.node[1].name}
You can parse the input string to JSONValue and then cast it to JSONOject as like shown below
JSONObject inp = (JSONObject) JSONValue.parse(request.getParameter("param1"));
The svenson JSON library can also be used from JSP.
You've got several syntax errors in your example code.
First, request.getParameter returns a String, so setting it to a JSONObject won't work. Secondly, your for loop is incomplete.
I suggest looking into the various JSON libraries available for Java and using one of those.
To help get you started, I'd look at some decoding samples.
In general, you won't be passing JSON within query parameters -- too much quoting needed. Rather, you should POST with JSON as payload (content type 'application/json') or such.
But beyond this, you need a json parser; Json.org lists tons; my favorite is Jackson, which like most alternatives from the page can also be invoked from jsp.

How to compare hash map key dynamically inside the closure in Grails?

Here I have hash map passed from the controller to GSP page.
Controller:
Map<String, List<String>> nameFiles = new HashMap<String, List<String>>();
nameFiles.put('patient1',["AA","BB","CC"]);
nameFiles.put('patient2',["DD","EE","FF"]);
model.put("nameFiles", nameFiles);
GSP page:
var patient = getPatient(); // lets say we get random patient through some jQuery function, could be not available in the nameFiles key
//check If nameFiles contain key same as patient varaible
<% nameFiles.each { fm -> %>
<% if (fm.containsKey(patient)) { %> // This if statement cannot compare dynamic sting varaaible. How to do this.
alert("Yes nameFiles contain the patient");
<% } %>
<% } %>
Assuming you have :
Map<String, List<String>> nameFiles = new HashMap<String, List<String>>();
nameFiles.put('patient1',[id:1,name:'Fred'])
nameFiles.put('patient2',[id:2,name:'Tom'])
It is as simple as this to get current patient:
<% def aa = nameFiles?.find{it.key=='patient1'}?.value %>
<g:if test="${aa}">
// we definitely have ${aa} and it has been made null safe
<g:if>
This returns {id:1, Name:Fred} on gsp which is the list iteration
My goodness all that else if it is as if you are in a controller, I understand why you are having to do this but it isn't good practice you could just create a tagLib that takes current value and processes the entry according to something in a given list or maybe against db fresh on the fly all correctly presented produced.
Final edit whilst you can declare variables like jsp you can also use
<g:set var="aa" value="${nameFiles?.find{it.key=='patient1'}?.value}" scope="page|session|..."/>
By default variable is set for the page but could be made into a session variable either way it is a lot cleaner than <% %>
Hopefully final edit
I think people should think carefully about what their actual problem is and try to present the problem clearly otherwise the audience ends up answering something else due to the poor quality of the post.
If I understand correctly you have something happening in a controller as in some list being produced. The missing bit must be you are then doing some form of form check maybe a select box selection that then ends up in jquery by that you mean you have some form of java script check going on against a form field check.
There are two ways of pumping such information into the javascript world for such purposes
Method 1:
//I haven't tested this, hopefully gives you the idea
var array = []
<g:each in="${namedFiles}" var="${pa}">
array.push({code:'${pa.key} listing:'${pa.value}'})
</g:each>
Method 2
Controller
//where you now push named files as a json
return [namedFiles as JSON].toString()
// or alternatively in gsp javascript segment something like this
var results=$.parseJSON('<%=namedFiles.encodeAsJSON()%>');
var results = results['patient1']
Honestly speaking I didn't get what are you asking and what kind of problem do you have as a result, but I guess that you tried to implement something like that:
<g:if test="${nameFiles[patient]}">
alert("Yes nameFiles contain the patient");
</g:if>
As you may be noticed I tried to avoid the scriptlet mess and used grails custom tags.
Also I hardly imagine how are you going to call the jQuery function to get a variable and then use it for generating a view on the server side. But try to define some mock "patient" variable at first to test my sample.
If the "patient" variable value is only available at the client side - so you have to change the approach and generate your alerts not on the server.
UPD
From the other hand you could return your nameFiles as JSON in your controller and then parse this JSON with javascript on the client side like that:
var nameFiles = JSON.parse("${nameFiles}")
if (nameFiles.hasOwnProperty(patient)) {
alert("Yes nameFiles contain the patient");
}
I haven't test this code, but at least you are pointed that gsp are rendered on server and you can convert your map to JSON, pass it to the view, parse with JavaScript and generate the needed alert.
Variable Declaration in GSP
You can declare variables within <% %> brackets:
<% patientIdentifier = 'randomName' %>
For more details see the Grails documentation on Variables and Scopes.
Checking if Patient is contained in namedFiles
You don't need to iterate over the map. Just checking the map if it contains the key.
// check if nameFiles contains key same as patient variable
<% if (nameFiles.containsKey(patient)) { %>
alert("Yes nameFiles contains the patient");
<% } %>

Use a complex java map in a jquery function

In a .jsp page I have a complex java map, like this:
Map<UserDefinedType, Map<String, Boolean>> allMaps= (Map)request.getAttribute("allMaps");
I need to use this map in a jquery function. Is there any way to achieve this?
The jquery function looks like this:
$('#selectMenuId').click(function(){
var val =$('#selectMenuId').val();
var allMaps= <%= allMaps%>
// Is there any way to access all the keys and values of this allMaps variable?
});

Interaction between JSP and External javascript files

I am newbie to external javascript files (*.js). Basically I have my JSP ready but my manager wants me to add graphics in it.
So I found some *.js files. But I don't know how to communicate between them and my JSP page.
I want to pass data from jsp to external .js file.
Is there any mechanism to do that?
For e.g:-
Demo.jsp
out.print(request.getAttribute("Name"));
Now I want use/pass/set above value to main.js file how to do that?
<script type="text/javascript">
var myJavascriptVariable = <%= request.getParameter("Name")%>;
//or .getAttribute("Name")
</script>
This could do the trick, it will make a global Variable which could be accessed in main.js. When you have GET Parameters you could also use only JS:
var paramarr = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < paramarr.length; i++) {
var tmparr = paramarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
or a bit shorter:
var params = {};
// parse URL's GET parameters and iterate over them
window.location.search.substr(1).split("&"),forEach(function(el) {
var kv = el.split('"'); // split into [ key, value ] array
params[kv[0]] = kv[1];
});
Now you can access the parameter in JS via:
params['name']
Personally I would use AJAX (e.g. with the help of JQuery) to get Data for my JavaScript files, you can look at that at http://api.jquery.com/category/ajax/shorthand-methods/ (2018 edit: kust use native ajax calls or whatever JS framework is hyped this week ;-) )
If you are using .js file you can't write jsp sriptlet in it.
If you need to call value in .js file there is one simple way.
Assign values to input elements in .jsp page.(If you are not using values in .jsp page assign values to hidden input elements)
Then include.js file in your .jsp page
get values as javasript or jquery methods.
Ex:-
value= document.getElementById("element_id").value
OR If you are using jquery you can get as
value = $("#element_id").val();
You can declare a global js variable and assign the value.
<% String myValue = (String)request.getAttribute("Name"); %>
var global1 ='<%= myValue %>';

Display java list data in jsp after jsp is displayed

I am new to Java EE programming. Following my understanding on jsp. Corret me if I am wrong
- JSP pages are converted to servlet first then to html and resulted html page is displayed in browser.
Now suppose jsp page is displayed in browser i.e now it is html page and I have a java List which have names or some sort of data that I want to print on the currently loaded page. I can get the List object using ajax but the how will I display it on html as html cant render java collections.
Correct me wherever I misunderstood the flow or basic concepts.
Thanks.
You could use ajax (using jQuery would be easy) to make a call to your Servlet
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { param1: "val1" , param2: "val2" }
}).done(function( data) {
//TODO
});
}
Now on Servlet, in doPost(), Use Gson to generate JSON representation for your collection
String parameter1 = request.getParameter(param1);
String parameter2 = request.getParameter(param2);
//call to service to generate the collection
//for example List<Employee>
List<Employee> employees = someService(parameter1, parameter2);
//using google's gson
Gson gson = new Gson();
String json = new Gson().toJson(employees);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Now we have response in javascript function as a array of javascript objects, So modify it to
}).done(function( data) {
//some processing for display
var len = data.length
for (var i=0; i<len; ++i) {
var employeeFirstName = data[i].firstName;
var employeeLastName = data[i].lastName;
//set it to some DIV, or do the processing you want
}
}
});
Also See
How to call a java method from jsp by clicking a menu in html page?
You need to send the contents of your list as text to the user's browser (which is what normally happens).
A convenient format for transferring the contents of the list between the browser and the server is JSON, due to its simple readability with JavaScript and easy generation on the server.
You can then display the returned text in whatever way you like using JavaScript.
A JSP is compiled into a java servlet class, which can handle HTTP requests. When the servlet is deployed to an application server HTTP requests are passed to the servlet for handling: an HTTP response is generated which normally contains some HTML, a status code, etc.
So it's the java code in the servlet which loops over your list and presumably generates the appropriate HTML to render that list in a browser.
Whether or not it's an AJAX request or not doesn't really matter. Rather than rendering a full HTML page, the AJAX request would probably be handled by a different servlet, which generates only a partial page - perhaps just the <ul><li>...</li></ul> to render your list. The javascript in your HTML page can then take care of updating the user interface by replacing the old version of the list.

Categories

Resources