JavaWeb study notes (11)

History books show

 

Session

session overview

  • In WEB development, the server can be created for each user's browser session objects (session objects), Note: a browser exclusively a session object (by default). Thus, when the need to save user data, the server program may be written to the user data of the user exclusive browser session, when a user uses a browser to access other programs, other program can be taken out from the user data in the user's session, as customer service.
  • The main difference is that the Session and Cookie:

l Cookie is the user data addressed to the user's browser.

l Session technique the user data written to the user exclusive session. Presence server, there is also the tomcat

Session object is created by the server, developers can call the request object's method getSession get the session object.

  • Each browser stores its own data to the Session
  • Session data can not be shared by other browsers
  • Session generally useful for determining whether a user is logged
package com.zx.web.servlet.lesson04;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/Lesson04Servlet1")
public class Lesson04Servlet1 extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // the TODO Auto-Generated Method Stub 
        
        // acquired by Session Object Request 
        the HttpSession the session = the req.getSession ();
         // save data to the Session 
        session.setAttribute ( "name", "ZX" ); 
    } 
}
package com.zx.web.servlet.lesson04;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/Lesson04Servlet2")
public class Lesson04Servlet2 extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // the TODO Auto-Generated Method Stub 
        
        // acquired by Session Object Request 
        the HttpSession the session = the req.getSession ();
         // Get Session value 
        String name = (String) session.getAttribute ( "name" ) ;
         // response to the client 
        resp.getWriter () Write (name);. 
    } 
}

After a browser to get the value, other browsers will get less than the

After you close your browser, reopen, is a new session, so the session is also changed.

Session can be simply understood as follows: the user to open a browser, click multiple hyperlinks to access multiple web server resources, then close the browser, the whole process is called a session.

 

Session of questions

Question: how to implement a server session to a user's browser services?

v server assigns a session ID for each browser, and the Session ID by the client stored in the form Cookie

Session implementation principle:

  1. When a browser to access the background, the background will create a Session object, and assign an id
  2. Session Id through this Cookie response header returned to the client in the form of
  3. The client will put ji there is a local (browser) Cookie
  4. The next time you visit the site, will session id in the form of a cookie request header back to back
package com.zx.web.servlet.lesson07;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
        resp.setHeader("content-type", "text/html;charset=utf-8");
        //1.获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String client_code=req.getParameter("code");
        
        //2.获取服务端的code
        String server_code=(String) req.getSession().getAttribute("code");
        
        if(server_code == null ) { 
            . resp.getWriter () Write ( "Refresh on a clear page" ); 
        } 
        
        // 3. Comparative codes 
        IF (! {server_code.equalsIgnoreCase (client_code)) 
            resp.getWriter () Write. ( "inconsistent verification code" ); 
        } the else {
             // resp.getWriter () Write ( "inconsistent verification code");. 
            IF ( "ZX" .equals (username) && "123" .equals (password)) { 
                RESP . .getWriter () Write ( "successful login" ); 
            } the else { 
                . resp.getWriter () Write ( "Login failed");
            }
        } 
        
        // 4. The verification code is deleted from the server
         // the req.getSession () removeAttribute ( "code");. 
        The req.getSession () the invalidate ();. // all the data are deleted Session 
        
    } 
}
package com.zx.web.servlet.lesson07;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.dsna.util.images.ValidateCode;

/**
 * Servlet implementation class ValidateCodeServlet
 * 验证码的Servlet
 */
@WebServlet("/ValidateCodeServlet")
public class ValidateCodeServlet extends HttpServlet {
    

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ValidateCode vc=new ValidateCode(100, 30, 4, 6);
        
        System.out.println("生成的验证码:"+vc.getCode());
        
        //把验证码存在session
        request.getSession().setAttribute("code", vc.getCode());
        
        vc.write(response.getOutputStream());
    }

}

HttpSession common method

  • The data stored in the HttpSession object, the object is a domain object.
  • void setAttribute (String name, Object value); a data memory
  • Object getAttribute (String name); fetch
  • void removeAttribute (String name); delete the data of a key
  • HttpSession.getId()
  • setMaxInactiveInterval (int interval) set the survival time of the session
  • invalidate () so that this session is invalid

 

getSession (): implementation of the principles of the internal

HttpSession request.getSession (): internal implementation of the principle of

1, to get the name of the value of the cookie JSESSIONID.

2, there is no such cookie, create a new HttpSession object, assign a unique SessionID, and wrote a name to the client as a cookie JSESSIONID = sessionID

3, there is such a Cookie, get the value of the cookie (ie HttpSession value of the object) to find that the HttpSession object from the server's memory based on ID:

Found: Remove continue to serve you.

Not found: 2 from the start.

 

HttpSession request.getSession(boolean create)

parameter:

true: and getSession () function the same.

false: According to the client JSESSIONID value of the cookie, and find the corresponding HttpSession object, can not find return null (does not create a new, just the query).

Browser pass Sessionid, but the server does not have the corresponding object id, the server returns null

Session state in three ways:

Created: When the browser first accesses the server resources dynamically created

Alive: The server application is running

death:

Session.invalidate (); compulsory destruction

Timeout: 30 minutes by default

setMaxInactiveInterval (int) in seconds

 

Session persistence

Save memory space;

Ensure that the server reboot or restart a single Web application can respond to the session before the restart;

Method: The above desired class implement Serializable (session storage object implementation)

 

JSP:

When accessing lesson1.jsp, you will first compile lession1_jsp.java, and then compiled into lession1_jsp.class

  • JSP stands for Java Server Pages, and it servle technologies, are technologies for developing dynamic web resources defined by SUN. JSP / Servlet specification. JSP is actually a Servlet. 
  • JSP biggest feature of this technology is that, as written in jsp write html, but it is, can only provide static html data for the user compared to html, the technology allows for nested and Jsp java code in the page to provide users dynamic data.

jsp best practices

  • Servlet: controller. Key to write java code logic (get form data, business logic processing, distribution steering)
  • JSP: template code is displayed. Emphasis display data

Demos: JSP form can also handle the request, but generally not so used by the Servlet to deal with form

Note: request, out, response called JSP built-in objects, need not be declared directly

.Jsp two ways to specify the methods can be:

1. Add the project name

2. Direct write .jsp file name

  1. Small script <% java code%>
  2. Expression <3% + 2% => Out.print equivalent to the (2 + 3);
  3. Statement <%!%> Represent members define global, static blocks class.

 

JSP comments: <% - the content of the comment -%> Features: Safety, provincial traffic

Comment pages: <! - Comment page -> Features: insecurity, traffic charges

Page

Attributes:

Less: self-study

session: Will automatically create session objects. The default value is true;

buffer: JSP has javax.servlet.jsp.JspWriter output character stream. Settings. Cache size of the output data, the default is 8kb

isErrorPage: whether to create a throwable object. The default is false;

Common: Demo

import and the import java code is the same

<%@ page import="java.util.Date,java.util.List"%>

or:

<%@ page import="java.util.Date"%>

<%@ page import="java.util.List"%>

Note: the JSP automatically import the following packages:

import java.lang.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

errorPage: If there is an error page, then jump to a specific resource

errorPage = "/ uri" If you write "/" represents the directory application, the absolute path of the current.

If you do not write "/" represents a relative path.

 There are / is to find the path from the WebContent

contextType: equivalent to response.setContextType ( "text / html; charset = utf-8");

pageEncoding: tell the JSP engine encoded files used for translation.

isELIgnored: whether to support EL expressions. The default is false

include

Static include: the other resources included in the current page.

<%@ include file="/include/header.jsp" %>

Dynamic include:

<jsp:include page="/include/header.jsp"></jsp:include>

 

The difference: the translation of different time periods

The former: put the two papers merged in the translation

The latter: the file will not be merged, the code is executed when the include, contain only the contents of another file.

 jsp refers to the process of translation: when .jsp file access, h will turn into a .jsp then into .class .java

Principle: do not use static move.

 

JSP six common actions:

Common actions JSP 6

  • <Jsp: include> includes another jsp dynamic content into the current jsp page
  • <Jsp: forward> forwards the request (corresponding to the forwarding request)
  • <Jsp: param> parameter setting request           
  • <Jsp: useBean> to create an object
  • <Jsp: setProperty> to the specified object property assignment
  • <Jsp: getProperty> Remove the specified object property value

 

 id with the following object name is associated

 

Guess you like

Origin www.cnblogs.com/zhangwugai/p/11390882.html