Session Introduction and examples in servlet

Source: Internet
Author: User

HttpServletRequest has two overloaded getSession () methods. One accepts a boolean value and the other does not contain any parameters. The getSession () method has the same function as the getSession (true) method, if the corresponding client has generated a session, the old session will be returned. Otherwise, this method will generate a session ID and bind it with the corresponding client, if getSession (false) indicates that the corresponding client already has a corresponding session, the old session will be returned. Otherwise, no new session will be generated. You can use the isNow () method on the HttpSession object to determine whether the session is a newly created

Common HttpSession Methods

Public void setAttribute (String name, Object value)
Bind the value object to the session with the name

Public object getAttribute (String name)
Obtains the property value of name. If the property does not exist, null is returned.

Public void removeAttribute (String name)
Delete the name attribute from the session. If the attribute does not exist, it will not be executed or thrown an error.

Public Enumeration getAttributeNames ()
Returns the enumerated values related to the session.

Public void invalidate ()
Invalidates sessions and deletes attribute objects.

Public Boolean isNew ()
Used to check whether the current customer is a new session

Public long getCreationTime ()
Returns the session creation time.

Public long getLastAccessedTime ()
Returns the time when the web Container receives the client's final request within the session time.

Public int getMaxInactiveInterval ()
Returns the maximum time for a customer request within the session period to be in seconds.

Public void setMaxInactiveInterval (int seconds)
Maximum time allowed for client requests

ServletContext getServletContext ()
Returns the context of the current session. The ServletContext object allows the Servlet to communicate with the web container.

Public String getId ()
Returns the identification number during the session.

A simple example of saving information to a session

Sessionlogin.html
Copy codeThe Code is as follows:

<Meta name = "keywords" content = "keyword1, keyword2, keyword3"/>
<Meta name = "description" content = "this is my page"/>
<Meta name = "content-type" content = "text/html; charset = UTF-8"/>

<! -- <Link rel = "stylesheet" type = "text/css" href = "./styles.css"> --> </pre>
<Form action = "servlet/saveinfo" method = "post">
User name:
<Input type = "text" name = "username"/> <input type = "submit"/>

Password:
<Input type = "password" name = "userpasswd"/>

</Form>
<Pre>

</Pre>
</Div>
<Div>

Copy codeThe Code is as follows:
Package chap03;

Import java. io. IOException;
Import java. io. PrintWriter;

Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import javax. servlet. http. HttpSession;

Public class saveinfo extends HttpServlet {

/**
* Constructor of the object.
*/
Public saveinfo (){
Super ();
}

/**
* Destruction of the servlet.

*/
Public void destroy (){
Super. destroy (); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet.

*
* This method is called when a form has its tag value method equals to get.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws ServletException if an error occurred
* @ Throws IOException if an error occurred
*/
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {

// Put the user name in the session if the user has entered the user name
If (request. getParameter ("username ")! = Null );
{
HttpSession session = request. getSession ();
Session. setAttribute ("username", request. getParameter ("username "));
}
Response. setContentType ("text/html; charset = GBK ");
PrintWriter out = response. getWriter ();
Out. println ("session created ");
Out. println ("
");
Out. println ("jump to another <a> page </a> ");

}

/**
* The doPost method of the servlet.

*
* This method is called when a form has its tag value method equals to post.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws ServletException if an error occurred
* @ Throws IOException if an error occurred
*/
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {

DoGet (request, response );
}

/**
* Initialization of the servlet.

*
* @ Throws ServletException if an error occurs
*/
Public void init () throws ServletException {
// Put your code here
}

} </Pre>
</Div>
<Div>


Copy codeThe Code is as follows:
Package chap03;

Import java. io. IOException;
Import java. io. PrintWriter;

Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Import javax. servlet. http. HttpSession;
Public class getsession extends HttpServlet {

/**
* Constructor of the object.
*/
Public getsession (){
Super ();
}

/**
* Destruction of the servlet.

*/
Public void destroy (){
Super. destroy (); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet.

*
* This method is called when a form has its tag value method equals to get.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws ServletException if an error occurred
* @ Throws IOException if an error occurred
*/
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {

Response. setContentType ("text/html; charset = GBK ");
PrintWriter out = response. getWriter ();

String username = "";
// The created session is not created here.
HttpSession session = request. getSession ();
// If you have obtained the result, it indicates you have logged on.
If (session! = Null)
{
Username = (String) session. getAttribute ("username ");
Out. println ("Get created Session ");
Out. println ("
");
Out. println ("Login Name:" + username );
}
Else
{
Response. sendRedirect ("../sessionlogin.html ");
}
}

/**
* The doPost method of the servlet.

*
* This method is called when a form has its tag value method equals to post.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws ServletException if an error occurred
* @ Throws IOException if an error occurred
*/
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}

/**
* Initialization of the servlet.

*
* @ Throws ServletException if an error occurs
*/
Public void init () throws ServletException {
// Put your code here
}

} </Pre>
</Div>
<Div> </div>
<Div>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.