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 :)
Related
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)" />
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");
<% } %>
I know its easy to use values of form ,from jsp to java,But how to use a variable value of JSP code into java class.
For e.g., I want to use value of vlaue in a java class
any help will be appreciated,thanx
<%
String value=null;
value= (String) session.getAttribute("name");
%>
Please be more specific. Where you need to access your request or session data?
You can get all data at you servlet code the same way as at JSP (i fact, JSPs are being compiled to servlets behind the curtain):
request.getSession().getAttribute("some");
If the data comes from a jsp/html then you should use:
request.getParameter("value")
if the data is saved in the session then get it from the session using:
req.getSession().getAttribute("value");
Then I also suggest you ensure it is not null:
String value = (String) request.getParameter("value");
if(value != null){
// the value is at the form, so you can get it and use it
}
else{
//the value is not at the html or the value is not given a value
}
hello i need to output a java variable inside a javascript call inside a tag inside a jsp !
for example:
<% String param = "hello";%>
<dmf:checkbox name="checkbox"
onclick = "selectAll(<%=param%>)"
/>
the javascript generated is:
selectAll(<%=param%>),this); but I actually want something like
selectAllCheckBoxes(Hello),this);
That's not escaping. That's just printing a scriptlet variable as if it is a JavaScript variable.
Besides, your examples are confusing, they doesn't match each other and the Javascript code is syntactically invalid. I can at least tell that JavaScript string variables are to be surrounded by quotes. If you want to end up with
selectAllCheckBoxes('Hello', this);
where Hello should be obtained as a value of the scriptlet local name variable (the param is a reserved variable name, you shouldn't use it yourself), then you need to do
selectAllCheckBoxes('<%= name %>', this);
In the same way, if you want to end up with
onclick="selectAll('Hello')"
you need to do
onclick="selectAll('<%= name %>')"
That said, I strongly recommend you to stop using the old fashioned scriptlets which are been discouraged since more than a decade. JSP programmers were been recommended to use taglibs and EL only to make the JSP code more clean and robust and better maintainable. You can use taglibs such as JSTL to control the flow in the JSP page and you can use EL to access the "back-end" data. Your example can be replaced by:
<c:set var="name" value="Hello" />
...
selectAllCheckBoxes('${name}', this);
Generate the whole attribute value with a scriptlet, like this:
<dmf:checkbox name="checkbox"
onclick = "<%= "selectAll(" + param + ")" %>" />
maybe you are trying to achieve this?
var myVar = '<%= (String)request.getParameter("tab") %>';
loadtabs(myVar);
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)