Solved

How can i list/show all session variables

Posted on 2006-10-23
5
4,720 Views
Last Modified: 2011-08-18
In ASP i am able to list all session variables and corresponding values.
How can i do this in JSP?

0
Comment
Question by:dayiku
  • 4
5 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 50 total points
ID: 17790558
does this help:
http://javaalmanac.com/egs/javax.servlet/State.html

   // Get all request-scoped attributes
    java.util.Enumeration enum = req.getAttributeNames();
    for (; enum.hasMoreElements(); ) {
        // Get the name of the attribute
        String name = (String)enum.nextElement();
   
        // Get the value of the attribute
        Object value = req.getAttribute(name);
    }
   
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 17790566
try:

<%
      /*
            Version: 1.1 : 1st Nov 2004
            Author: ryancys
            Get Session Object and values
      */
%>
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<%!
      public static Vector chklist = new Vector();
      
      public static String chkopt(String v1, String v2, String rv){
            if (v1.equals(v2)) {
                  return rv;
            } else {
                  return "";
            }            
      }
%>
<%
      //Clear Cache
      if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
            response.setHeader("Pragma", "no-cache");
      } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
            response.setHeader("Cache-Control", "no-cache");
      }
      response.setDateHeader("Expires", 0);
      
      //Check to clear Session
      if (request.getMethod().equalsIgnoreCase("POST")) {
            session.invalidate();
      }
      
      
      String sessionFileName = "session.txt";
      File datafile = null;
      BufferedReader in = null;
      
      String line = "";
      String loadtype = (request.getParameter("loadtype")==null?"":request.getParameter("loadtype").toString().trim());
      long i = 0;
      String tmp = "";
      boolean isItemFound = false;
      
      chklist.clear();
      
      if ((!loadtype.equals("")) && (!loadtype.equals("default"))) {
            sessionFileName = loadtype;
      }
      
      datafile = new File(application.getRealPath("/jsp/"+sessionFileName));
      
      //System.out.println(application.getRealPath("/jsp/"+sessionFileName));
      //System.out.println("datafile.exists() = "+datafile.exists());
      
      if (datafile.exists()) {
            in = new BufferedReader(new FileReader(datafile));
            while ((line = in.readLine()) != null) {
                  try {
                        if (!line.trim().equals("")) {
                              chklist.add(line.trim());
                        }
                  } catch (Exception e) { }
            }
      }      
      
      for (int s=0;s < chklist.size();s++) {
            System.out.println("chklist["+s+"] = " + chklist.get(s).toString());
      }
%>
<html>
<head>
<title>Get Session</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF" text="#000000">
<p><font face="Arial, Helvetica, sans-serif" size="2"><b>Session List: <%=loadtype%></b></font></p>
<% if ((loadtype.equals("")) || (loadtype.equals("default"))) { %>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr bgcolor="#CCCCCC">
    <td width="33" height="29"><b></b></td>
    <td width="259" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Attribute
      name</font></b></td>
    <td width="50%" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Value</font></b></td>
    <td width="143" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Type</font></b></td>
  </tr>
  <%
    java.util.Enumeration enum = null;
      try {
            enum = session.getAttributeNames();
      } catch (Exception e) {}
      Object curAttribute = null;
      String attName = null;
      i = 0;
      if (enum != null) {
            while (enum.hasMoreElements())
            {
                  attName = (String)enum.nextElement();
                  curAttribute = session.getAttribute(attName);
                  i++;
  %>
  <tr>
    <td width="33"><font face="Arial, Helvetica, sans-serif" size="2"><%=i%></font></td>
    <td width="259"><font face="Arial, Helvetica, sans-serif" size="2"><%=attName%></font></td>
    <td width="50%"><font face="Arial, Helvetica, sans-serif" size="2"><%=curAttribute%></font></td>
    <td width="143"><font face="Arial, Helvetica, sans-serif" size="2"><%=curAttribute.toString().length()+";"+curAttribute.getClass()%></font></td>
  </tr>
  <%       }
        }      
      %>
</table>
<% } else { %>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr bgcolor="#CCCCCC">
    <td width="33" height="29"><b></b></td>
    <td width="259" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Attribute
      name</font></b></td>
    <td width="50%" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Value</font></b></td>
    <td width="143" height="29"><b><font face="Arial, Helvetica, sans-serif" size="2">Type</font></b></td>
  </tr>
  <%
    i = 0;
            
      for (int n=0;n < chklist.size();n++) {
            
            System.out.println("chklist["+n+"] = " + chklist.get(n).toString());
            
            isItemFound = false;
            java.util.Enumeration enum = null;
            try {
                  enum = session.getAttributeNames();
            } catch (Exception e) {}
            Object curAttribute = null;
            String attName = null;
            if (enum != null) {
                  while (enum.hasMoreElements())
                  {
                        attName = (String)enum.nextElement();
                        if (attName.equals(chklist.get(n).toString())) {
                              curAttribute = session.getAttribute(attName);
                              i++;
  %>
  <tr>
    <td width="33"><font face="Arial, Helvetica, sans-serif" size="2"><%=n+1%></font></td>
    <td width="259"><font face="Arial, Helvetica, sans-serif" size="2"><%=attName%></font></td>
    <td width="50%"><font face="Arial, Helvetica, sans-serif" size="2"><%=curAttribute%></font></td>
    <td width="143"><font face="Arial, Helvetica, sans-serif" size="2"><%=curAttribute.toString().length()+";"+curAttribute.getClass()%></font></td>
  </tr>
  <%                        isItemFound = true;            
                                break;      
                          }      
                    }
              }
            if (isItemFound == false) {
                  if (chklist.get(n).toString().equals("")) {
                        tmp = "";
                  } else {
                        tmp = String.valueOf(n+1);
                  }
            %>
        <tr>
            <td width="33"><font face="Arial, Helvetica, sans-serif" size="2"><%=tmp%></font></td>
            <td width="259"><font face="Arial, Helvetica, sans-serif" size="2"><%=chklist.get(n).toString()%></font></td>
            <td width="50%"><font face="Arial, Helvetica, sans-serif" size="2">&nbsp;</font></td>
            <td width="143"><font face="Arial, Helvetica, sans-serif" size="2">&nbsp;</font></td>
        </tr>
        <%
            }
             
        }      
      %>
</table>
<% } %>
<p><font face="Arial, Helvetica, sans-serif" size="2"><b>Total Session Object
  Count: <%=i%></b></font> <br>
  <br>
</p>
<form name="form1" method="post" action="getsessionlist.jsp" onsubmit="return confirm('Are you sure want to clear the Session objects?');">
  <select name="loadtype">
    <option value="default" <%=chkopt(loadtype,"","selected")%>>Using Default</option>
      <option value="session.txt" <%=chkopt(loadtype,"session.txt","selected")%>>Using session.txt</option>    
      <option value="creditcard.txt" <%=chkopt(loadtype,"creditcard.txt","selected")%>>Using creditcard.txt</option>      
  </select>
  <input type="submit" name="Submit" value="Expire Session Now">
  <input type="button" name="Refresh" value="Refresh" onClick="javascript:window.location.href='getsessionlist.jsp?loadtype='+document.form1.loadtype.options[document.form1.loadtype.selectedIndex].value;">
</form>
<p>&nbsp; </p>
</body>
</html>


try amend accordingly, hope this helps.
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 17790579
generally, can try like this:

Enumeration enum = session.getAttributeNames();
Object curAttribute = null;
String attName = null;
while (enum.hasMoreElements())
{
    attName = (String)enum.nextElement();
    curAttribute = session.getAttribute(attName);
    out.println("Attribute name: " + attName);
    out.println("Type: " + curAttribute.getClass());
    out.println("<BR>");
}

http:Q_20874109.html
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 17790589
ahhh, post a wrong one.. what i mean is this..

java.util.Enumeration enum = session.getAttributeNames();
     Object curAttribute = null;
     String attName = null;
      Hastable ht=new Hashtable();
     while (enum.hasMoreElements())
     {
          attName = (String)enum.nextElement();
          curAttribute = session.getAttribute(attName);
          ht.put(curAttribute,attName);
    }

( sorry, angelIII )
0
 
LVL 49

Expert Comment

by:Ryan Chong
ID: 17790606
java.util.Enumeration enum = session.getAttributeNames();
     Object curAttribute = null;
     String attName = null;
     
    while (enum.hasMoreElements())
     {
          attName = (String)enum.nextElement();
          curAttribute = session.getAttribute(attName);
          out.println("Attribute name: " + attName);
          out.println("Attribute value: " + curAttribute);
          out.println("<BR>");
    }
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you work with shopping cart / ecommerce relates web sites, you need to pass the certain form post details to the payment gateway process page with required details for the products items you give to order. Also you may need to track the ordered…
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now