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");
<% } %>
Related
I'm trying to loop through an ArrayList in start.jsp and pass each item into a different jsp, destination.jsp. I am currently using sessions, and I am aware that the session.setAttribute function will overwrite whatever the previous values of the attribute were. Here is my code:
start.jsp:
// Main AL has the type ArrayList<ArrayList<String>>. I am trying to loop through the mainAL and pass each item in it to destination.jsp.
...
// This snipet of code creates a button for each element in mainAL and submits the element to destination.jsp when clicked.
for (ArrayList<String> al : mainAL)
{
<form action="destination.jsp" method="get">
<input type="submit"/>
</form>
<% session.setAttribute("list", al); %>
}
...
destination.jsp:
...
<% ArrayList<String> result = (ArrayList<String>) session.getAttribute("list"); %>
<%out.println(list);%>
...
If the mainAL has more than 1 item, every destination.jsp instance generated from the for loop will only show the last ArrayList from mainAL. How should I fix this problem? Is there any way to pass each ArrayList to destination.jsp without its value being overwritted?
The session.setAttribute() function sets a value globally. It means, that you overwrite the value in every loop cycle. You will have to make hidden inputs, in witch you put your data, so it gets passed as a GET argument in the request url to your other destination site. At the destinations site you will have to retrieve that data from the request url. You can you use POST as well, when you want to keep your url clean. I would also recommended doing things like this with a session token instead of passing lists through inputs.
I hope that this helped you :)
I fetched data(some strings) from the database and i covered each string in a link in A.jsp page . Now if clicked a link,then the string that covered by the link is displayed in B.jsp . Here i note that in database i stored an image as a string .So here string is nothing but an image.
<% ResultSet rs=st.executeQuery("Select name,image from base64image");
int ii=0;
while(rs.next()){
if(ii==0)
out.println("<tr>");
ii=1;
%>
<td> <img src='<%=rs.getString(2)%>' height='200px;' width='200px' />n</td>
<%
i++;
if(i%3 ==0 ){
out.println("</tr>");
ii=0;
}
}
out.println("</tr> </table>");
}
Ok, so looking at your code, your using the expression tags for outputting the string you need. This string is the image source path, and the image is then used as the click link for your B.jsp page.
I'm assuming this expression is java, since the variable your using has a object type, and respective "getString()" method. If this is the case your code doesn't show the above "rs" object to be in jsp <% %> tags. Any java you write in jsp files need to be in these tags.
<% ResultSet rs=st.executeQuery("Select name,image from base64image"); %>
This being said using java in scriptlets in this manner is generally considered bad practice, however, I could understand the want to clean up the jsp file, and minimize the amount of lines to accomplish the query. This being said, just for completion's sake of this answer, this is how you might accomplish the same thing using jstl tags:
//first include the sql tag library in your Jsp
<%# taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
<sql:query dataSource = "datasource/here" var = "result">
//full query here
SELECT * from Employees;
</sql:query>
//You can then use the result variable using standard jsp
//Here you can grab the row, or sift through multiple results, etc.
<c:forEach var = "row" items = "${result.rows}">
<img src='${row.columnName}' height='200px;' width='200px' />n
</c:forEach>
info and examples here
However this is a lot of code in your jsp that isn't even the best way of going about this. Because you're only expecting one row returned, you would be forced to handle the results as if it returned multiple rows. (which is great however, if you needed to put this information into a table format)
The other solution would be to use java servlets. I can't fully recommend this though, as I don't know the structure of your code. This could either be easy, or difficult to implement into your system. However this still doesn't beat the one-line approach.
If you were to accomplish this via a separate servlet class, you would essentially call the class via an ajax call in the jsp, or using other various methods mentioned in this answer.
I hope I helped you solve your issue, and help any other people who stumble upon this answer!
Pass an Id with anchor tag in A.jsp
' <img src='c%>
Now in B.jsp retrives all the names 1st column value from the database.If it matches with this id's value,then show the image by using tag
<img src="<%=rs.getString(2)" />
The following line of java code is giving me null pageContext.getRequest().getParameter("id");
When I print it out in jsp page using <%=request.getAttribute("id")%> I am able to see the data stored inside.
Is there another way to retrieve the data from the jsp page and assign it to a java variable?
Yes you can do it. Place your code between <% %>
<%
String userID = request.getParameter("userid");
out.println(userID);
%>
If you want to avoid scriptlets you can use JSTL:
<c:set var="userId" value="${param.usedId}"/>
In JSP you can use internal java function
if do you want to pull a query parameter you simply have to write
<%request.getParameter("id") %>
if do you want to assign something like you want to put a data inside P tag you simply have to write
<p><%=request.getParameter("message")%></p>
in this case your java message will be inside P tag
and like javascript variable
<script>var id=<%=request.getParameter("id")%></script>
here you have assigned id (javascript variable) with query parameter pulled from native java function, id do you want to assign normal java variable inside jsp you have simply write
<% String message=request.getParameter("message")%>
Hope this help :)
I have a JSP where I'm using a javascript framework to build a chart using the Google Visualization API.
My servlet is returning a sales hashmap object with year as the key and integer (sales number) as the value.
My javascript uses the sales object to add data to the Google chart API which builds my chart.
code:
sales = '<%= session.getAttribute("sales") %>';
The sales object in my js gets the hashmap but it's a long string. Do I have to parse it in my javascript or is there a way it will automatically put the hashmap object properly into the javascript sales object?
you wont need to use an external json library (but you could!) - you can print out the json directly into a javascript variable like:
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<script>
(function(){
var sales = {
<c:forEach var="entry" items="${requestScope['sales'].entrySet}" varStatus="counter">
'${entry.key}' : ${entry.value} //outputs "2000" :1234 ,
<c:if test="${!counter.last}">, </c:test>
</c:foreach>
};
//js code that uses the sales object
doStuffWith(sales);
})()
</script>
Java and Javascript are completely different languages. Javascript doesn't know what do do with a Java HashMap object (actually in your example you'll get the output of HashMap.toString()). You'll have to serialize it into some form that Javascript will understand, eg. JSON.
Try using JSON which will allow you to describe your Java object in json ( java script object notation ) That way you can load the described object directly into javascript.
All this piece of code
sales = '<%= session.getAttribute("sales") %>';
does is print the value of session.getAttribute("sales") to the HTML output. Without any logic on your part as to how to format the output, Java will merely call .toString() on that Object - which the default implementation (unless you override it) usually results in an output that looks like classname#1234abc12.
So the short answer is that yes you will need to put in some logic on the Java side as far as how you would like your object / data structure to be output into the HTML document.
So according to my JSP reference book, as well as every other reference I can find on the web, I'm supposed to be able to do something like:
<%# tag dynamic-attributes="dynamicAttributesVar" %>
and then when someone uses an attribute that I didn't define in an attribute directive, I should be able to access that attribute from the "dynamicAttributesVar" map:
<%= dynamicAttributesVar.get("someUnexpectedAttribute") %>
However, that doesn't work, at all; I just get a "dynamicAttributesVar cannot be resolved" error when I try.
Now, I did discover (by looking at the generated Java class for the tag) that I can "hack" a working dynamic attributes variable by doing:
<% Map dynamicAttributesVar = _jspx_dynamic_attrs; %>
Now, that hack doesn't work unless I also use the dynamic-attributes parameter on my tag directive, so it seems that the parameter is doing something.
But what I want to know is, how can I make it do what it does for every other JSP user out there?
Just trying to get a badge for answering a four year old question.
I have this problem as well and came across some help at O'Reilly to use JSTL instead of scriptlets.
The original poster could have used this code to get all keys/values:
<c:forEach items="${dynamicAttributesVar}" var="a">
${a.key}="${a.value}"
</c:forEach>
This would get a specific value:
<c:out value="${dynamicAttributesVar['someUnexpectedAttribute']}"/>
Isn't "dynamicAttributesVar" the name of the key in the page context that the dynamic attributes are put into? So you could do
<c:out value="${dynamicAttributesVar.someUnexpectedAttributes}"/>
or if you must use scriptlets:
Map dynamicAttributes = (Map) pageContext.getAttribute("dynamicAttributesVar")
(Disclaimer: I haven't tried it, I've just used dynamic attributes in tags with direct Java implementations... but it seems reasonable)