Looping through an ArrayList and updating an attribute - java

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 :)

Related

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");
<% } %>

Can not get select list back in struts Action class in java

I have a list i take it from DB and populate to the page using this code
DynamicComboCM allPartners = new DynamicComboCM();
allPartners.setAllRecommendedList(daoClass.getAllPartners(ds));
request.setAttribute("allPartners", allPartners);
Here DynamicComboCM is bean that contains the property allRecommendedList and i populate this list from DB using daoClass which returns an ArrayList then i set it to request and get it on jsp page like this.
<html:select styleId="partnerListForRecommended" name="Bean2"
property="bean2Property" size="15" multiple="true">
<html:optionsCollection name="allPartners"
property="allRecommendedList" label="label" value="value" />
</html:select>
i get the list on jsp as expected, on jsp user moves some records from this list to another list and in this way this list reduced by size as some recoreds had move to other list. now when i press save button i m not getting this list,
can any one please help me how to get this list again in jsp, i tried it using request.getAttribute("allPartners"); but not working.
Thanks in advance.
One of solution is to put list allPartners into session.
to set
request.getSession().setAttribute("allPartners", allPartners);
to get when needed
request.getSession().getAttribute("allPartners");
Another solution (using request scope) is to get allPartners from database again (better from the cache).

Collect user input in Servlet and return at the same point to continue program: Java

I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.

I am able to get a list object but how do you display values in a list?

I am able to get the list object but how do you display values in a list???
<%
com.ibm.commerce.utf.objects.RFQProdAccessBean ab= new com.ibm.commerce.utf.objects.RFQProdAccessBean();
Enumeration list = (java.util.Enumeration)ab.findByRFQId(java.lang.Long.parseLong("13001"));
System.out.println("*******"+list);
Vector aVector = new Vector(java.util.Arrays.asList(list));
Iterator nums = aVector.iterator();
while(nums.hasNext()) {
String aString = (String)nums.next();
System.out.println("************"+aString);
}
%>
<c:out value="${aString}" />
You have several problems in your code:
java.util.Arrays.asList(list) won't transform an Enumeration into a List. It will create a List containing a single element: the enumeration. You should use Collections.list() to do that.
There is no reason to transform a List into a Vector. Vector (like Enumeration, by the way) is an old class that shouldn't be used anymore, and List has all you need.
You should use generic types and not raw types. It would save youmany unnecessary casts
This code shouldn't be in a JSP in the first place, but in a servlet or controller
You're trying to access aString from outside the loop, but aString is defined inside the loop
The JSP EL doesn't access local variables. It accesses page, request, session or application attributes. If you want it to access a local variable, you need to store this variable in a page scope attribute.
I guess you want to display every string in the enumeration. In that case, you should use the c:forEach tag, and not a while loop.
So, the code could be written as such:
<% RFQProdAccessBean ab= new RFQProdAccessBean();
Enumeration<String> enumeration = (Enumeration<String>) ab.findByRFQId(13001L);
pageContext.setAttribute("list", Collections.list(enumeration));
%>
<c:forEach var="element" items="${list}">
<c:out value="${element}"/>
</c:forEach>
But, I repeat, the Java code should be out of the JSP, and should store the list into a request attribute. The forEach loop would stay unchanged.

How to put a list in session and use it inside Javascript

I have a list of notification messages which I extract from the databse and put in the session in a servlet. This is then forwarded to a jsp page using requesDipstacher.forward(request,response). I now take the List of messages and loop it through using jstl :
<c:foreach value = "item" items = '${sessionScope.notification}'>
<a href = "javascript:printAll('${item}'}>Print</a>
</c:foreach>
The javascript looks like this
function printAll(item)
{
display(item) //note this is pseudo code . Here I kind of display the items.
}
Now my problem is there are far too many links displaying print in my webpage. I want to send the whole list into the javascript and iterate over it and display the individual messages. Is this possible with javascript.Kindly point me to an identical question if it exists.
If you don't have problem with put the javascript in the same file of the page, you could put something like this:
<script>
function printAll()
{
var html = '<ul>';
<c:foreach value = "item" items = '${sessionScope.notification}'>
html += '<li>${item}</li>';
</c:foreach>
html += '</ul>';
display(html);
}
</script>
Print
As you notice it, there are various ways to solve the problem.

Categories

Resources