java_ first year _JavaWeb (6)

Conversation

Session: from closed to open a browser to access the server to process the browser, which we call a session;

During the browser and server interaction, it will inevitably produce some of the data, and to save the corresponding data for each user, using two techniques: Cookie and the Session;

Cookie

Client technology, the server sends the user data is written in the form of a cookie for each client, which when accessed again, it will bring the relevant data so that the server can distinguish between data to the client;

Cookie in java class is created by javax.servlet.http.Cookie; method thereof are provided:

Cookie (String name, String value); // instantiate the Cookie object, passing its name and value 
public String getNme (); // get the name of Cookie's 
public String getValue (); // get the value of Cookie 
public  void setValue ( newValue String); // set the value of Cookie 
public  void setMaxAge ( int expiry); // set Cookie maximum storage time 
public  int getMaxAge (); // get Cookies validity of the unit is second 
public  void setPath (String uri); // set the cookie valid path, that path during which access is built cookie's 
public String getPath (); // obtain a valid path of the cookie
public  void setDomain (String pattern); // set the cookie domain effective 
public String getDomain (); // obtain a valid domain of the cookie

Cookie use each browser are set a Cookie, and check whether the request has been carrying the cookie as:

import javax.servlet.http.Cookie;
PrintWriter out = resppnse.getWriter();
Cookie[] cookies = request.getCookies();
if (cookies != null){
    for (int i = 0,i<cookies.length,i++){
        Cookie cookie = cookies[i];
//找到所要核对的cooki名
        if (cookie.getName().equals("lastaccesstime")){
            Long  lastaccesstime = Long.parseLong(cookie.getValue());
            Date date = new Date(lastaccesstime);
            out.write (Date.toLocaleString ()); // converts the cookie value before the date format and outputs 
            } 
        } 
    } the else { 
        out.write ( "first visit to the site" ); 
    } 
cookies cookie = new new cookies ( "lastacccesstime", System.currentTimeMillis () + ""); // whether first visit are cookie set the current time value 
response.addCookie (cookie); // add a new cookie to the response and output to client    

An information identifies only a Cookie, i.e., a web site may be transmitted to a plurality of sites with a browser, a browser may also be stored at different sites identified Cookie;

If you do not use getMaxAge () cookie will be saved to your hard drive, then that information is stored in memory, that you log in again close the browser can not find the original Cookie information; when you delete Cookie their time that is set to 0 equivalent to delete;

It requires URLEncoder class encode (String s, String enc) method when storing Chinese Chinese transcoding;

Cookie cookie = new Cookie("name",URLEncoder.encode("小兆","UTF-8"));

URLEncoder class is also used decode (String s, String enc) acquiring decoding Chinese cookie;

URLDecoder.decode(cookies[i].getValue(),"UTF-8");

Session

Each user's browser server creates a Session object, used to store user data when the user accesses the server to other programs, other programs can be taken out of the user's data through the user's Session, for customer service is;

The main difference is with Cookie: Cookie is addressed to the browser, while the Session is present in the server, when you need to call, the request object methods to get getSession Session object;

getSession () method will automatically determine whether an existing session, if any, is invoked, if not, it is created; and a session will have its own ID is sent in the form of a cookie to the browser, so getSession () method should exist sessionID create and pass it to Cookie objects procedure;

Determine whether an existing session:

= The session the HttpSession Request.getSession (); 
session.setAttribute ( "Data", "small Precursors"); // remember the foregoing character code need to be changed ". 8-UTF" 
String the sessionID = session.getId ();
 IF (the session .isNew ()) { 
    response.getWriter () Print (. "created successfully, the session id which is:" + the sessionID); 
} the else { 
     . response.getWriter () Print ( "session already exists, which is the session id : "+ the sessionID); 
     }

The session object 30 minutes by default is not used, the server automatically destroyed session, can manually configure the expiration time of the session in web.xml;

<session-config>
        <session-timeout>12</session-tiomeout>
</session-config>

Prevent multiple submission form

Preventing the client:

<% @ Page Language = "Java" Import = "Classes in java.util. *" The pageEncoding = "UTF-. 8"%> 
<! DOCTYPE the HTML> 
<HTML> 
  <head> 
    <title> Form1 form </ title> 
        <Script type = "text / JavaScript"> 
        var isCommitted = to false ; // whether the form has been submitted identifier defaults to false 
        function the dosubmit () {
             iF (== isCommitted to false ) { 
                isCommitted = to true ; // after submitting the form, whether the form submit identity is set to true 
                return  to true ;// returns true so that the normal form submission 
            } the else {
                 return false;//返回false那么表单将不提交
            }
        }
    </script>
  </head>
  
  <body>
      <form action="${pageContext.request.contextPath}/servlet/DoFormServlet" onsubmit="return dosubmit()" method="post">
        用户名:<input type="text" name="username">
        <input type="submit" value="提交" id="submit">
    </form>
  </body>
</html>

It can be controlled through the use of JavaScript itself of its submission;

Preventing the end of the service, the server generates a unique identifier, called a token Token; Token stored in the user's session and sent to Form form, but the form that uses a hidden form

Token field to store, when submitted together submitted to the server, then the server compares the session in accordance with the Token and Token is submitted, if the same is submitted successfully, and the Token information is deleted after the success in the session ; If the server is not found or form or a Token carries values ​​do not match, then reject the form submission;

 To generate a unique identification code and stored in the session, then xxx.jsp Jump to page:

TokenProccessor.getInstance token = String () makeToken ();. // Create a token 
request.getSession () setAttribute ( "token", token);.   // use the session save token (tokens) in the server 
request.getRequestDispatcher ( " /xxx.jsp").forward(request, the Response); // Jump to page form.jsp

Xxx.jsp editor page, set from the form, use hidden fields to store Token:

<form action="${pageContext.request.contextPath}/xxx" method="post">
    <input type="hidden" name="token" value="${token}"/>
    用户名:<input type="text" name="username"> 
    <input type="submit" value="提交">
</form>

Token comparison value and form submission up session object storage server determines whether the processing request:

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

public class DoFormServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            boolean b = isRepeatSubmit(request);//判断用户是否是重复提交
            if(b==true){
                System.out.println("Please do not send" );
                 return ; 
            } 
            Request.getSession () removeAttribute (. "Token"); // remove the token session 
            System.out.println ( "processing user submits a request !!" ); 
        } 
        
        / ** 
         * Analyzing submitted by the client and server side up tokens generated token are the same 
         * @param Request 
         * @return  
         * repeat the user submits the form to true 
         * repeat the user does not submit the form to false 
         * / 
        Private  Boolean isRepeatSubmit (the HttpServletRequest Request) { 
            String client_token = request.getParameter ( "token" );
             //1, if the form is not user-submitted data token, the user submits the form is repeated 
            IF (client_token == null ) {
                 return  to true ; 
            } 
            // remove the token is stored in Session 
            String server_token = (String) request.getSession ( ) .getAttribute ( "token" );
             // 2, if the token (token) Session current user does not exist, the user submits the form is repeated 
            IF (server_token == null ) {
                 return  to true ; 
            } 
            // . 3, stored in Session token token (token) with the form submission (tokens) are different, the user submits the form is repeated 
            IF (! {client_token.equals (server_token))
                 return  to true ;
            }
            
            return false;
        }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

On the front of the token to create a method to realize we can own, to ensure its uniqueness;

Guess you like

Origin www.cnblogs.com/lzj-learn/p/11613702.html