getting session variables from session - java

I am getting the below error when I compile the below code
Enumeration e = bean.getSession().getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
Error:
found : java.util.Iterator
required: java.util.Enumeration
Enumeration e = bean.getSession().getAttributeNames();

You shouldn't be using an enumeration, it should be an Iterator. Then use the methods of the Iterator like hasNext() to check if there is a next item and next() to get the next item. Hope it helps :)

how about just using a for loop?
for (String name : bean.getSession().getAttributeNames() ) {
String value = session.getAttribute(name).toString();
System.out.println( name + " = " + value );
}

It looks like you're actually using a getAttributeNames() method that return an instance of java.util.Iterator. So as a quick fix, this should work:
Iterator it = bean.getSession().getAttributeNames();
while (it.hasNext()) {
String name = (String)it.next();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
More help/info could be provided if we knew the actual types of the bean variable and/or the return value of bean.getSession().

I think the problem is in the first line. This works for me:
<%
Enumeration attrs = session.getAttributeNames(); //you will need to include java.util.Enumeration
while(attrs.hasMoreElements()){ //for each item in the session array
String id = attrs.nextElement().toString(); //the name of the attribute
out.print("'" + id + "': '" + session.getAttribute(id) + "'"); //print out the key/value pair
}
%>
As others pointed out though, you should be using an Iterator

Related

disassemble object in array

I have a search method in the database that brings me the following result:
As you see that inside the Object [4] comes another array containing People, Pessoas, and PessoasEnderecos and more objects that have relantionship with Pessoas.
I would like it to return only this way and not inside another array as it is happening now, it should look like this:
elementData=Object[10](id=144)
[0]=Pessoas(id=166)
[1]=PessoasEnderecos(id=167)
...
i have this method:
#RequestMapping(method = RequestMethod.GET, value = "/pessoas")
public ResponseEntity<Collection<Pessoas>> buscarPessoas(HttpServletRequest request) throws Exception {
String idEntidadeCrypt = request.getHeader("DataBase");
Long idEntidade = Long.parseLong(Crypto.decode(idEntidadeCrypt));
Collection<Pessoas> pessoasBuscados = pessoasService.buscarFiltro(idEntidade);
return new ResponseEntity<>(pessoasBuscados, HttpStatus.OK);
}
and :
#Repository
public interface PessoasRepository extends JpaRepository<Pessoas, Integer> {
#Query( value="select pes, pEnd, pFis, pJur "
+ "from "
+ "Pessoas pes, "
+ "PessoasEnderecos pEnd,"
+ "PessoasFisicas pFis,"
+ "PessoasJuridicas pJur"
+ " where "
+ "pes.entidade.idEntidade = pEnd.entidade.idEntidade "
+ "and pes.idPessoa = pEnd.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pFis.entidade.idEntidade "
+ "and pes.idPessoa = pFis.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = pJur.entidade.idEntidade "
+ "and pes.idPessoa = pJur.pessoa.idPessoa "
+ "and pes.entidade.idEntidade = :parametroId " )
public Collection<Pessoas> encontrar(#Param("parametroId") Long usuarioEntidade);
how can i solve that ?
ArrayList<> does not work with magic, it has an actual implementation. elementData is the array where it stores its elements. As you can see (that is a link in the previous sentence), it is a private member of the class, so you do not interact with it, but you see it in a debugger because it exists.
If you want to return an array instead of a List, you can always use toArray() which all Lists implement.

iterate over a set and create a string containing HTML

I have the following code that is used in the Image gallery generating program Jalbum to generate all keywords used for the images in the gallery.
Set allKeywords = new HashSet();
for (AlbumObject ao : currentObjects) {
XmpManager mgr = ao.getXmpManager();
if (mgr != null) {
allKeywords.addAll(mgr.getKeywordSet());
}
}
//get the Iterator
Iterator itr = allKeywords.iterator();
while(itr.hasNext())
out.println(itr.next());
My question is when out.print:
out.println(itr.next());
how can I add html to each individual keyword? I basically want to outprint:
keyword
I am a newbie in this realm so please be gentle!
out.println("" + itr.next() + "");
If you want to call iterator.next() two times
out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + itr.next() + "\">"
+ (itr.hasNext() ? itr.next() : "") + "</a>");
For your requirement I hope mgr.getKeywordSet() returns string
String str = itr.next();
System.out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + str + "\">" + str + "</a>");

retrieve values after iteration

After iterating over a "hashmap list", I want to write the values into a string as 'value 1' and 'value 2'. I cannot figure how?Can someone help me!
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
I have 2 values in my data. The above code gives me
Con:Name
Con:ID
Now, I want 'Name' to be value 1 and 'ID' to be value 2 so that I can replace and write them in the following string
"xxxxxxxxxx"+key+"xxxx"+value 1+"xxxxxxxxx"+value 2+"xxxxxxxxxx";
Try:
String value1="";
String value2="";
int counter=0;
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
if(counter==0) {//first pass assign value to value1
value1=listItem;
counter++;//increment for next pass
}else if(counter==1) {//second pass assign value to value2
value2=listItem;
counter++;//so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(value1);//should display 'Name'
System.out.println(value2);//should display 'ID'
Using the StringBuilder class (assuming key is defined outside of the loop)
StringBuilder sb = new StringBuilder("xxxxxx" + key + "xxxx");
for (Object listItem : (List)value) {
System.out.println(key + ":" + listItem);
sb.append(listItem+"xxxxxxxxx");
}

Adding the results to an arraylist

I am facing some difficulties while assigning the values in an array list. My code is :
while (answer.hasMore()) {
SearchResult rslt = (SearchResult)answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println();
if (attrs.get("department") != null && attrs.get("telephonenumber") != null) {
System.out.println(attrs.get("department") + " " + attrs.get("name") + " " +
attrs.get("Description") + " " + attrs.get("mail") + " " +
attrs.get("telephonenumber")+
attrs.get("samaccountname") + attrs.get("samaccountname") );
}
I want to assign the values of attrs.get("department") + attrs.get("description")+ attrs.get("name")+attrs.get("mail") each one to an array list.
I tried to define at the beginning:
String[] name = new String[100];
and in the while loop i tried to read the name attribute, I tried to do:
name = attrs.get("name");
But it did not work. Can anyone help.
In Java, an array and an ArrayList are quite different.
String[] name_array = new String[100];
creates a fixed-length array of Strings, but
ArrayList name_list = new ArrayList();
creates a variable-length ArrayList of objects (it will grow as you add more objects).
To add an object to an ArrayList, you can use its add() method.
name_list.add("Hello");
However, with an array you need to set the object at a specific index, e.g:
name_array[23] = "Hello";
You need to read a basic tutorial on the Java language and standard library.
You cannot directly assign strings to a array made of string "references". You need to index it first. But it would be much better to actually use a list (and maybe convert it to an array later). Check out List and ArrayList in the Java documentation.
As an example:
Attributes attrs = new Attributes();
List<String> attribValues = new ArrayList<String>();
System.out.println();
if (attrs.get("department") != null
&& attrs.get("telephonenumber") != null) {
System.out
.println(attrs.get("department") + " " + attrs.get("name")
+ " " + attrs.get("Description") + " "
+ attrs.get("mail") + " "
+ attrs.get("telephonenumber")
+ attrs.get("samaccountname")
+ attrs.get("samaccountname"));
attribValues.add(attrs.get("department"));
attribValues.add(attrs.get("telephonenumber"));
}
final String[] attribArray = attribValues.toArray(new String[attribValues.size()]);
First of all define your name as String not as an array of String like this:
String name;
And then read name as:
name = attrs.getString("name");
Now coming back to your issue of populating List, I am sure you will get ready-made answers here but I suggest you to do some reading on how to create and populate a List in Java.

Request.getParameterMap values not castable to string

i am trying to get the complete parameter map from the request object and iterate over it.
here is the sample code
Map map = request.getParameterMap();
for(Object key : map.keySet()){
String keyStr = (String)key;
Object value = map.get(keyStr);
System.out.println("Key " + (String)key + " : " + value);
}
output
Key businessunit : [Ljava.lang.String;#388f8321
Key site : [Ljava.lang.String;#55ea0889
Key startDate : [Ljava.lang.String;#77d6866f
Key submit : [Ljava.lang.String;#25141ee0
Key traffictype : [Ljava.lang.String;#4bf71724
its evident from the output that the value object is an instance of String
now when i change my code to something like this
Map map = request.getParameterMap();
for(Object key : map.keySet()){
String keyStr = (String)key;
Object value = map.get(keyStr);
if(value instanceof String)
System.out.println("Key " + (String)key + " : " + (String)value);
}
it prints nothing but as per the previous output it should have printed the values and if i remove instanceOf check it gives ClassCastException. is this the expected behavior or i am doing something wrong here ?
[Ljava.lang.String;#XXXXXXX means it is array of String not a single String. So your condition fails and it does not print anything.
As the object which is returned is an array of strings as Harry Joy pointed out, you will have to use the Arrays.toString() method in order to convert that array to a printable string:
Map map = request.getParameterMap();
for (Object key: map.keySet())
{
String keyStr = (String)key;
String[] value = (String[])map.get(keyStr);
System.out.println("Key" + (String)key + " : " + Arrays.toString(value));
}
The value is an array. If you're sure that the array is not empty, you should get the string value like this:
String value = (String) map.get(keyStr)[0];

Categories

Resources