Solved

How can i list/show all session variables

Posted on 2006-10-23
5
4,723 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 50

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 50

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 50

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 50

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Format results with PHP 3 77
I starting with php 12 133
website content maintenance 3 96
Cordova Camera plugin fails 2 120
Preface This article introduces an authentication and authorization system for a website.  It is understood by the author and the project contributors that there is no such thing as a "one size fits all" system.  That being said, there is a certa…
Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

803 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