L6Day5: Jsp built-in objects 2

1. What is the session

  1. Session represents a conversation client and server
  2. Web of the session refers to the user when browsing a Web site, enter from the browser to the browser closes the elapsed period of time, that is, users browse the site takes time
  3. Can be seen from the above definition, session time is actually a particular concept

 

For example, our online shopping:

User login -> Add to Cart -> Fill orders -> submit orders -> order confirmation -> Payment

The whole shopping process belongs to a session

 

It holds different users in the server's memory session

uploading.4e448015.gifUploading ... re-upload canceled

Session object

  1. JSP Session object is a built-in objects
  2. Session object is created automatically when a JSP page is first loaded, to complete the session manager
  3. Open a browser from a user and link to start the server, close to the client browser leaves the server end, is called a session
  4. When a user accesses a server, might switch between several pages of the server, the server should know that this is a user, you need to use the session object (storing user information) by some way
  5. Session object is an instance of class HttpSession

Session object commonly used method:

Long getCreationTime () Returns the session creation time

The unique ID number when Public String getId () Returns the session to create a set of JSP engine for it

Public Object setAttribute (String name, Object value) with the specified name to the object bound to this session

Public Object getAttribute (String name) Returns the name of this session object binding together, if not, return null

String [] getValueNames () returns an array of all the session attributes contained in this

Int getMaxInactiveInterval () Returns the two long interval this session request is canceled (time in seconds)

<h1>session对象</h1>
<hr>
Session的创建时间:<%=session.getCreationTime()%><br>(单位是毫秒)

可以将此时间格式化:
<%
	SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
	Date date = new Date(session.getCreationTime());
	String dateStr = Sdf.format(date);
%>
Session创建的时间: <%=dateStr%>

<%session.setAttribute(“username”,”admin”);%>
Session的ID编号:<%=session.getId()%>
从session获取的用户名:<%=session.getAttribute(“username”);%>

在session1.jsp中写下面代码:
<%session.setAttribute(“username”,”admin”);%>
Session的ID编号:<%=session.getId()%>
从session获取的用户名:<%=session.getAttribute(“username”);%>
<a href=”session2.jsp”>点我跳转到session2.jsp</a>
在session2.jsp中写下面的代码:
<%session.setAttribute(“username”,”admin”);%>
Session的ID编号:<%=session.getId()%>
从session获取的用户名:<%=session.getAttribute(“username”);%>

发现:session2.jsp中的sessionID和session1.jsp中的sessionID是一样的,而且,在session1.jsp中设置的用户名,在session2.jsp中也能取到。
因此,也验证了上面所说的,用户从打开浏览器链接到服务器时session开始,到关闭浏览器结束服务器时,session结束。在这个过程中是一个session,且它当中的信息是共享的.


在session1.jsp中输入:
<%
		session.setAttribute("password", "123");
		session.setAttribute("age", 25);
	%>
在session2.jsp中:
session中的属性有:<%
	String[] names = session.getValueNames();
	for(int i=0;i<names.length;i++){
		out.print(names[i]+"&nbsp;&nbsp;&nbsp;");
	}
%>


设置session的失效时间:
在session1.jsp中输入:
<%session.setMaxInactiveInterval(10);//单位是秒%>
<a href=”session2.jsp”>点我跳转到session2.jsp</a>
Session的ID编号:<%=session.getId()%>

在session2.jsp中输入:
Session的ID编号:<%=session.getId()%>

然后点开session1.jsp10秒后,点超链接跳转,发现session2.jsp的ID和session1.jsp的ID是不一样的。因为已经过期了,又创建了一个。

Session Life Cycle

  • create:

       When the client first visit to a jsp or Servlet, the server creates a sessionId for the current session, each time a client sends a request to the server, this will carry sessionId past, the server will be sessionId this school experience.

 

  • activity:
    1. Belonging to a session with a session via a hyperlink to open a new page.
    2. Belonging to the same session as long as the current session page is not fully closed, re-open a new browser window to access the same project resources.
    3. Unless all pages and browsers of this session are closed and then re-visit a Servlet or jsp will create a new session.

Note: the original session still exist, the old sessionId still exist in the server, but the client will no longer carry it and then handed over to the server check. (After the session failure does not exist)

  • destroy:

       Session destruction only three ways:

    1. Call session.invalidate () method
    2. Session expired (timeout)
    3. The server restarts

 

Set the session timeout:

Tomcat default session timeout is 30 minutes

Set session timeout in two ways:

the setMaxInactiveInterval (time); // time in seconds

In web.xml configuration:

<session-config>

       <session-timeout>

              10

       </session-timeout>

</ Session-config> .// minutes when the unit

Application Object

Application object:

  1. Application object implements the sharing of data between users, you can store global variables
  2. Application servers are beginning to start, stop, and server shutdown
  3. The connection between the user connected to the front or different users, may operate on the same property of the application object
  4. Anywhere in the operation of the application object properties, will affect other users of this access. (Similar modifications in Java static variables)
  5. Application ServletContext object is an instance of the class

 

Common methods are as follows:

Public void setAttribute (String name, Object value) with the specified name to the object bound to this session

Public Object getAttribute (String name) Returns the object with the specified name in this session bound together, if not, return null

Enumeration getAttributeNames () Returns an enumeration of all the names of available properties

String getServerInfo () returns the JSP (servlet) engine name and version number

Case:

<%

       application.setAttribute("city", "北京");

       application.setAttribute("postcode", "100000");

%>

城市:<%=application.getAttribute("city") %><br>

All attributes:

<%

       Enumeration names = application.getAttributeNames();

       while(names.hasMoreElements()){

              out.print(names.nextElement()+"<br>");

       }

%>

jsp engine name and version number: <% = application.getServerInfo ()%> <br>

page objects

page objects

       jsp page object is a built-in objects, refer to the current JSP page itself, similar to this keyword Java class, it is an instance of java.lang.Object class. Methods as below:

class getClass () Returns the class Object

int hashCode () Returns the hash code of the Object

Boolean equals (Object obj) determines whether the object is equal to the specified Object

Void copy (Object obj) to the copy of Object This object specified

Object clone () Clone this object is Object

String toString () converts the object into the object of this Object of the String Class

Void notify () wake up a thread waiting

Void notifyAll () wakes up all waiting threads

Void wait (int timeout) so that a thread is waiting until the end of the timeout or wake

Void wait () make a thread in wait until they were awakened

pageContext object

  1. pageContext JSP objects are built-in objects, it provides access to all objects and namespaces in a JSP page
  2. A property value pageContext object to access the page where the session, this may be taken to the page where the application of
  3. pageContext object is an instance of class PageContext

 

pageContext object:

JspWriter getOut () returns the current flow in response to the client using (out)

HttpSession getSession () returns the HttpSession object (session) of the current page

Object getPage () returns an Object object of the current page (page)

ServletRequest getRequest () returns the ServletRequest object of the current page (request)

ServletResponse getResponse () returns an object ServletResponse current page (response)

Void setAttribute (String name, Object value) to set property

Object getAttribute (String name, int scope) takes a value within a specified range of properties

Int getAttributeScope (String name) Returns a property of the scope

Void forward (String realtiveUrlPath) using the current page redirect to another page

Void include (String realtiveUrlPath) contains another file in the current location

 

Case:

用户名:<%=pageContext.getSession().getAttribute("username") %><br>

<%

       //pageContext.include("aa.jsp");

%>

<%

       pageContext.forward("index.jsp");

%>

 

Config object

Config object is at a Servlet initialization, JSP engine passing it information, the information includes the parameter Servlet initialization to use the (configured by the attribute names and values) and information on the server (by passing a ServletContext object), Methods as below:

ServletContext getServletContext () Returns the ServletContext object server related information

String getInitParameter (String name) Returns the value of the initialization parameter

Enumeration getInitParameterNames () returns the Servlet initialization parameters needed to enumerate all the

Exception objects

Exception object is a built-in objects JSP

Exception object is an exception object when a page exception occurs during operation, it creates the object.

If a page you want to apply for this object, it must take isErrorPage set to true, otherwise it is impossible to compile. Exception object is an instance of java.lang.Throwable. Methods as below:

String getMessage () returns a message describing the exception

String toString () returns a short description of the message about the exception

void printStackTrace () and displayed abnormal stack trace

Throwable fillInStackTrace () rewrite the exception stack trace execution

 

Case:

Note that the input is provided in index.jsp :( page in errorPage = "exception.jsp")

<%

       out.print(3/0);

%>

In the input exception.jsp :( note page provided in isErrorPage = "true")

Exception Message: <% = exception.getMessage ()%> <br>

Description: <% = exception.toString ()%>

Published 11 original articles · won praise 0 · Views 66

Guess you like

Origin blog.csdn.net/qq_16594593/article/details/104562909