Java/JSP/Session — различия между версиями

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

Текущая версия на 07:10, 1 июня 2010

Duplicated session varaibles

<jsp:useBean id="myBookBean"   class="com.jexp.Book"
             scope="session">
  <%-- The setProperty tag is only executed when a JavaBean is created --%>
  <jsp:setProperty name="myBookBean" property="author" value="Joe" />
</jsp:useBean>
<html>
  <head>
    <title>When a JavaBean already exists...</title>
  </head>
  <body>
    The author of your book is <jsp:getProperty name="myBookBean"
                                                property="author" /><P>
    Click  to see another page that
    declares a JavaBean that uses the same name and scope.
  </body>
</html>
//beanAlreadyExists2.jsp
<jsp:useBean id="myBookBean"   class="com.jexp.Book"
             scope="session" />
<html>
  <head>
    <title>When a JavaBean already exists...</title>
  </head>
  <body>
    This page redeclares the JavaBean, but does not set any of its properties.
    The same name and scope were used for the JavaBean, so the original bean
    is used.
    <P>
    The author of your book is <jsp:getProperty name="myBookBean"
                                                property="author" /><P>
  </body>
</html>





JSP and session

/*
<%@ page import="com.jexp.*"%>
<html>
<head>
</head>
<body>
<h1>Thankyou for your request</h1>
Thankyou for your request for more information.
It will be sent to you shortly.
<%
  MoreInfoRequest infoRequest = new MoreInfoRequest();
  infoRequest.setCourses(request.getParameter("courses"));
  infoRequest.setFirstName(request.getParameter("firstName"));
  infoRequest.setLastName(request.getParameter("lastName"));
  infoRequest.setEmail(request.getParameter("email"));
  // this is the method that will bind an object to a session
  session.setAttribute("infoRequest", infoRequest);
%>
<p>Click  to view your request.
</body>
</html>
*/
package com.jexp;
public class MoreInfoRequest
{
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getCourses() {
    return courses;
  }
  public void setCourses(String courses) {
    this.courses = courses;
  }
  public String getEmail() {
    return email;
  }
    public void setEmail(String email) {
    this.email = email;
  }
  private String firstName;
  private String lastName;
  private String email;
  private String courses;
}

<body>
<h1>Your Request</h1>
Here is the information that you submitted to us for processing.
<%
  MoreInfoRequest infoRequest =
             (MoreInfoRequest) session.getAttribute("infoRequest");
%>
<br>Course name:<b> <%=infoRequest.getCourses()%></b>
<br>Your name: <b><%=infoRequest.getFirstName()%>
<%=infoRequest.getLastName()%></b>
<br>Your email: <b><%=infoRequest.getEmail()%></b>
</body>
</html>





JSP and session 2

//sessionObject.jsp
<html>
<head>
<title>The Session Object</title>
</head>
<body>
<h1>The Session Object</h1>
Here are some properties of your session object.
<br>The session was created at <%= session.getCreationTime() %>
<br>The session has an inactive interval of <%= session.getMaxInactiveInterval() %>
<br>The session id is <%= session.getId() %>
</body>
</html>
///
//logout.jsp
<html>
<head>
<title>Log out</title>
</head>
<body>
<h1>Log Out Page</h1>
<%
if (session != null) {
  session.invalidate();
}
%>
You are now logged out. Bye
</body>
</html>





JSP: display a session info

<%@page contentType="text/html"%>
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.ru/jstl/fmt" prefix="fmt" %>
<html>
<head><title>View Session JSP </title></head>
<body>
<h2>Session Info From A JSP</h2>
The session id: 
<c:out value="${pageContext.session.id}"/>
<h3>Session date values formatted as Dates</h3>
<jsp:useBean id="timeValues" class="java.util.Date"/>
<c:set target="${timeValues}" value="${pageContext.session.creationTime}" property="time"/>
The creation time: <fmt:formatDate value="${timeValues}" type="both" dateStyle="medium" />
<br><br>
<c:set target="${timeValues}" value="${pageContext.session.lastAccessedTime}" property="time"/>
The last accessed time:  
<fmt:formatDate value="${timeValues}" type="both" dateStyle="short" />
<c:out value="${timeValues}"/>
</body>
</html>





JSP New Session Parameter

<%@ page import="java.util.*" %>
<%
  // add parameter to session
  String name = request.getParameter("name");
  String value = request.getParameter("value");
  if (name!=null && value!=null && name.length()>0) {
    session.setAttribute(name,value);
  }
  Date lastVisit = (Date)session.getAttribute("lastVisit");
  Date thisVisit = new Date();
%>
<HTML>
  <HEAD>
    <TITLE>Session List</TITLE>
  </HEAD>
  <BODY>
    <H1>Session List</H1>
    Last visit: <%= lastVisit %><BR>
    This visit: <%= thisVisit %><BR>
    Session ID: <%= session.getId() %><BR>
    Session max interval: <%= session.getMaxInactiveInterval() %><BR>
    <H2>Session parameters</H2>
    <%
      Enumeration enum = session.getAttributeNames();
      while (enum.hasMoreElements()) {
        String attribute = (String) enum.nextElement();
        out.println(""+attribute+"="+
          session.getAttribute(attribute)+"<BR>");
      }
        session.setAttribute("lastVisit",thisVisit);
    %>
    <H2>New session parameter</H2>
    <FORM>
        <P>Name: <INPUT TYPE="TEXT" NAME="name"></P>
        <P>Value: <INPUT TYPE="TEXT" NAME="value"></P>
      <INPUT TYPE="SUBMIT" VALUE="Add new value">
    </FORM>
  </BODY>
</HTML>





JSP session counter

//startPage.html
<html>
<head>
<title>Page 1</title>
</head>
<body>
<h1>URL Re-writing Demo</h1>
 to visit page 2.
</body>
</html>

///
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java.sun.ru/dtd/web-app_2_3.dtd">
<web-app>
  <listener>
    <listener-class>com.jexp.SessionCount</listener-class>
  </listener>
  <taglib>
    <taglib-uri>http://java.sun.ru/jstl/core</taglib-uri>
    <taglib-location>/WEB-INF/c.tld</taglib-location>
  </taglib>
</web-app>
//sessionCounter.jsp
<html>
<head>
<title>Session Counter</title>
</head>
<body>
<h1>Session Counter</h1>
On this server, there are currently
<%=com.jexp.SessionCount.getNumberOfSessions()%> active sessions.
</body>
</html>

package com.jexp;
import javax.servlet.http.*;
public class SessionCount implements HttpSessionListener
{
  private static int numberOfSessions = 0;
  public void sessionCreated (HttpSessionEvent evt)
  {
    numberOfSessions++;
  }
  public void sessionDestroyed (HttpSessionEvent evt)
  {
    numberOfSessions--;
  }
  // here is our own method to return the number of current sessions
  public static int getNumberOfSessions()
  {
    return numberOfSessions;
  }
}





JSP Session Parameter Rewrite

<%@ page import="java.util.*" %>
<%
  // add parameter to session
  String name = request.getParameter("name");
  String value = request.getParameter("value");
  if (name!=null && value!=null && name.length()>0) {
    session.setAttribute(name,value);
  }
  Date lastVisit = (Date)session.getAttribute("lastVisit");
  Date thisVisit = new Date();
%>
<HTML>
  <HEAD>
    <TITLE>Session List</TITLE>
  </HEAD>
  <BODY>
    <H1>Session List</H1>
    Last visit: <%= lastVisit %><BR>
    This visit: <%= thisVisit %><BR>
    Session ID: <%= session.getId() %><BR>
    Session max interval: <%= session.getMaxInactiveInterval() %><BR>
    <H2>Session parameters</H2>
    <%
      Enumeration enum = session.getAttributeNames();
      while (enum.hasMoreElements()) {
        String attribute = (String) enum.nextElement();
        out.println(""+attribute+"="+
          session.getAttribute(attribute)+"<BR>");
      }
        session.setAttribute("lastVisit",thisVisit);
    %>
    <H2>New session parameter</H2>
<% String url = response.encodeURL("session-rewrite"); %>
    <P>Form URL "<%= url %>"</P>
    <FORM ACTION="<%= url %>">
        <P>Name: <INPUT TYPE="TEXT" NAME="name"></P>
        <P>Value: <INPUT TYPE="TEXT" NAME="value"></P>
      <INPUT TYPE="SUBMIT" VALUE="Add new value">
    </FORM>
  </BODY>
</HTML>





Jsp Using Bean Scope Session

<%@ page errorPage="errorpage.jsp" %>
<jsp:useBean id="counter" scope="session" class="beans.Counter" />
<html>
  <head>
    <title>Session Bean Example 1</title>
  </head>
  <body>
    <H3>Session Bean Example 1</H3>
    <center><b>The current count for the counter bean is: </b>
      <%=counter.getCount() %></center>
  </body>
</html>





JSP: view session

<%@page contentType="text/html"%>
<%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.ru/jstl/fmt" prefix="fmt" %>
<html>
<head><title>View Session JSP </title></head>
<body>
<h2>Session Info From A JSP</h2>
The session id: 
<c:out value="${pageContext.session.id}"/>
<br>
<br>
The session creation time as a long value: 
<c:out value="${pageContext.session.creationTime}"/>
<br>
<br>
The last accessed time as a long value: 
<c:out value="${pageContext.session.lastAccessedTime}"/>
<br>
<br>
</body>
</html>





Print the request headers and the session attributes

<%--
  Copyright (c) 2002 by Phil Hanna
  All rights reserved.
  
  You may study, use, modify, and distribute this
  software for any purpose provided that this
  copyright notice appears in all copies.
  
  This software is provided without warranty
  either expressed or implied.
--%>
<%@ page
      errorPage="ErrorPage.jsp"
      import="java.io.*"
      import="java.util.*"
%>
<%
   Enumeration enames;
   Map map;
   String title;
   // Print the request headers
   map = new TreeMap();
   enames = request.getHeaderNames();
   while (enames.hasMoreElements()) {
      String name = (String) enames.nextElement();
      String value = request.getHeader(name);
      map.put(name, value);
   }
   out.println(createTable(map, "Request Headers"));
   // Print the session attributes
   map = new TreeMap();
   enames = session.getAttributeNames();
   while (enames.hasMoreElements()) {
      String name = (String) enames.nextElement();
      String value = "" + session.getAttribute(name);
      map.put(name, value);
   }
   out.println(createTable(map, "Session Attributes"));
%>
<%-- Define a method to create an HTML table --%>
<%!
   private static String createTable(Map map, String title)
   {
      StringBuffer sb = new StringBuffer();
      // Generate the header lines
      sb.append("<table border="1" cellpadding="3">");
      sb.append("<tr>");
      sb.append("<th colspan="2">");
      sb.append(title);
      sb.append("</th>");
      sb.append("</tr>");
      // Generate the table rows
      Iterator imap = map.entrySet().iterator();
      while (imap.hasNext()) {
         Map.Entry entry = (Map.Entry) imap.next();
         String key = (String) entry.getKey();
         String value = (String) entry.getValue();
         sb.append("<tr>");
         sb.append("<td>");
         sb.append(key);
         sb.append("</td>");
         sb.append("<td>");
         sb.append(value);
         sb.append("</td>");
         sb.append("</tr>");
      }
      // Generate the footer lines
      sb.append("</table><p></p>");
      // Return the generated HTML
      return sb.toString();
   }
%>





Sessions disabled

<%@ page session="false" %>
<jsp:useBean id="user" class="com.jexp.Book" scope="session" />
<html>
  <head><title>Attempt to use a session JavaBean with sessions disabled!</title></head>
  <body>
    This goes BANG!
  </body>
</html>





Use Session Jsp

<%@ page errorPage="errorpage.jsp" %>
<html>
  <head>
    <title>UseSession</title>
  </head>
  <body>
    <%
      Integer count = (Integer)session.getAttribute("COUNT");
      // If COUNT is not found, create it and add it to the session
      if ( count == null ) {
      
        count = new Integer(1);
        session.setAttribute("COUNT", count);
      }
      else {
        count = new Integer(count.intValue() + 1);
        session.setAttribute("COUNT", count);
      }  
      out.println("<b>Hello you have visited this site: "
        + count + " times.</b>");
    %>
  </body>
</html>





Using Sessions to Track Users

<%@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);
        %>
        <H1>Using Sessions to Track Users</H1>
        Session ID: <%=session.getId()%>
        <BR>
        Session creation time: <%=new Date(session.getCreationTime())%>
        <BR>
        Last accessed time: <%=new Date(session.getLastAccessedTime())%>
        <BR>
        Number of times you"ve been here: <%=counter%> 
    </BODY> 
</HTML>