Java Tutorial/JSP/Session

Материал из Java эксперт
Перейти к: навигация, поиск

Get Session ID, creation time and last accessed time

   <source lang="java">

<%@page import = "java.util.*" session="true"%> <HTML>

   <HEAD>
       <TITLE>Using Sessions to Track Users</TITLE>
   </HEAD> 
   <BODY>
       <% 
       Integer counter = (Integer)session.getAttribute("counter");
       if (counter == null) {
           counter = new Integer(1);
       } else {
           counter = new Integer(counter.intValue() + 1);
       }
       session.setAttribute("counter", counter);
       %>

Using Sessions to Track Users

       Session ID: <%=session.getId()%>
       
Session creation time: <%=new Date(session.getCreationTime())%>
Last accessed time: <%=new Date(session.getLastAccessedTime())%>
Number of times you"ve been here: <%=counter%> </BODY>

</HTML></source>





Reference Session Value Across JSP Page

   <source lang="java">

<html> <head>

 <title>Session Example</title>

</head> <body> <%

  String val = request.getParameter("name");
  if (val != null)
     session.setAttribute("name", val);

%>

Session Example

Where would you like to go?



Session Scope Bean

Counter.java



   <source lang="java">

package beans; public class Counter {

   private int counter = 0;
   public void setCounter(int value) 
   {
       this.counter = value;
   }
   public int getCounter() 
   {
       return this.counter;
   }
   public Counter() 
   {
   }

}</source>





Set and get variable to a session

   <source lang="java">

<HTML>

   <HEAD>
       <TITLE>Using the Application Object</TITLE>
   </HEAD>
   <BODY>

Using the Application Object

       <%
       Integer counter = (Integer)session.getAttribute("counter");
       String heading = null;
       if (counter == null) {
           counter = new Integer(1);
       } else {
           counter = new Integer(counter.intValue() + 1);
       }
       session.setAttribute("counter", counter);
       Integer i = (Integer)application.getAttribute("i");
       if (i == null) {
           i = new Integer(1);
       } else {
           i = new Integer(i.intValue() + 1);
       }
       application.setAttribute("i", i);
       %>
       You have visited this page <%=counter%> times.
       
This page has been visited by all users <%=i%> times. </BODY>

</HTML></source>