Java/JSP/Session
Содержание
- 1 Duplicated session varaibles
- 2 JSP and session
- 3 Thankyou for your request
- 4 Your Request
- 5 The Session Object
- 6 Log Out Page
- 7 Session List
- 8 URL Re-writing Demo
- 9 Session Counter
- 10 Session List
- 11 Using Sessions to Track Users
Duplicated session varaibles
<source lang="java">
<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" />
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> </source>
JSP and session
<source lang="java">
/* <%@ page import="com.jexp.*"%> <html> <head> </head> <body>
Thankyou for your request
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>
Your Request
Here is the information that you submitted to us for processing. <%
MoreInfoRequest infoRequest = (MoreInfoRequest) session.getAttribute("infoRequest");
%>
Course name: <%=infoRequest.getCourses()%>
Your name: <%=infoRequest.getFirstName()%>
<%=infoRequest.getLastName()%>
Your email: <%=infoRequest.getEmail()%>
</body>
</html>
</source>
JSP and session 2
<source lang="java">
//sessionObject.jsp <html> <head> <title>The Session Object</title> </head> <body>
The Session Object
Here are some properties of your session object.
The session was created at <%= session.getCreationTime() %>
The session has an inactive interval of <%= session.getMaxInactiveInterval() %>
The session id is <%= session.getId() %>
</body>
</html>
///
//logout.jsp
<html>
<head>
<title>Log out</title>
</head>
<body>
Log Out Page
<% if (session != null) {
session.invalidate();
} %> You are now logged out. Bye </body> </html>
</source>
JSP: display a session info
<source lang="java">
<%@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>
Session Info From A JSP
The session id: <c:out value="${pageContext.session.id}"/>
Session date values formatted as Dates
<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" />
<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>
</source>
JSP New Session Parameter
<source lang="java">
<%@ 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>
Session List
Last visit: <%= lastVisit %>
This visit: <%= thisVisit %>
Session ID: <%= session.getId() %>
Session max interval: <%= session.getMaxInactiveInterval() %>
Session parameters
<% Enumeration enum = session.getAttributeNames(); while (enum.hasMoreElements()) { String attribute = (String) enum.nextElement(); out.println(""+attribute+"="+ session.getAttribute(attribute)+"
"); } session.setAttribute("lastVisit",thisVisit); %>
New session parameter
<FORM><P>Name: <INPUT TYPE="TEXT" NAME="name">
Value: <INPUT TYPE="TEXT" NAME="value">
<INPUT TYPE="SUBMIT" VALUE="Add new value"> </FORM> </BODY>
</HTML>
</source>
JSP session counter
<source lang="java">
//startPage.html <html> <head> <title>Page 1</title> </head> <body>
URL Re-writing Demo
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>
Session Counter
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; }
}
</source>
JSP Session Parameter Rewrite
<source lang="java">
<%@ 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>
Session List
Last visit: <%= lastVisit %>
This visit: <%= thisVisit %>
Session ID: <%= session.getId() %>
Session max interval: <%= session.getMaxInactiveInterval() %>
Session parameters
<% Enumeration enum = session.getAttributeNames(); while (enum.hasMoreElements()) { String attribute = (String) enum.nextElement(); out.println(""+attribute+"="+ session.getAttribute(attribute)+"
"); } session.setAttribute("lastVisit",thisVisit); %>
New session parameter
<% String url = response.encodeURL("session-rewrite"); %>
Form URL "<%= url %>"
<FORM ACTION="<%= url %>">
Name: <INPUT TYPE="TEXT" NAME="name">
Value: <INPUT TYPE="TEXT" NAME="value">
<INPUT TYPE="SUBMIT" VALUE="Add new value"> </FORM> </BODY>
</HTML>
</source>
Jsp Using Bean Scope Session
<source lang="java">
<%@ page errorPage="errorpage.jsp" %> <jsp:useBean id="counter" scope="session" class="beans.Counter" /> <html>
<head> <title>Session Bean Example 1</title> </head> <body>
Session Bean Example 1
</body>
</html>
</source>
JSP: view session
<source lang="java">
<%@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>
Session Info From A JSP
The session id:
<c:out value="${pageContext.session.id}"/>
The session creation time as a long value:
<c:out value="${pageContext.session.creationTime}"/>
The last accessed time as a long value:
<c:out value="${pageContext.session.lastAccessedTime}"/>
</body>
</html>
</source>
Print the request headers and the session attributes
<source lang="java">
<%--
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 linessb.append("
");
sb.append(title);sb.append(" | ");
sb.append("|
---|---|
");
sb.append(key);sb.append(" | ");
sb.append("");
sb.append(value);sb.append(" | ");
sb.append("
// Return the generated HTML return sb.toString(); }
%>
</source>
Sessions disabled
<source lang="java">
<%@ 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>
</source>
Use Session Jsp
<source lang="java">
<%@ 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("Hello you have visited this site: " + count + " times."); %> </body>
</html>
</source>
Using Sessions to Track Users
<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>