On the Session of use (original)

On the Session of use (original)

1 Introduction

In java Session domain objects, data can be stored on the server side, it can store a variety of data types, compared to only cookie store the string, give developers the stored data to provide a great convenience, is an excellent the back-end developers have to master the technology. This time, I will first explain the life cycle of Session domain, combined with an example of a cookie and session and talk about them with each other generally use, as well as session activation, passivation of use.

Lifecycle 2.Session domain

2.1 Session created

Mentioned earlier, session domain is on the server side data store, then, it will be created in the Session when the user first accesses the server, i.e. the first access jsp pages or servlet. The data stored in the server, is not it will not produce the case and client correspondence it? There are two user access to your server, you give them, respectively, to create a property called "user" in Session, then how do you know what "user" corresponds to which users? So, in fact, while the Session is created, the browser will be added a cookie, his name is "JSESSIONID", it is a long random string, and the server can use this as a cookie to identify accurately access to the corresponding user. For example, user 1 "JSESSIONID" possibly "E39BB9C ...", and the user "JSESSIONID" 2 is "78DD984 ...".

2.2 Session destruction

Now, we already know how the session is created, but do not understand when he is destroyed, I believe we would not easily use. The server will not have a long time to clear out the session, the default time is 30 minutes and can be set in web.xml The tag Label, in minutes, for example, is 60, he will become the default time of the destruction of one hour. In another case, it is to call the session's invalidate method forces destroyed. This also led to the closure will be destroyed when the server session, due to shut down the server when the server will automatically call invalidate method to clear all session.

3. Then, after the session is destroyed, which is stored on the property does not have access not yet, what good policy?

The session of the Label to 10080 (60 24- 7), that is, the destruction of seven days? This is the worst, although without shutting down the server cookie can barely produce a similar effect of long-term storage of data. However, to know the data session is in the server's memory, with the increase of users, session domain object is bound to the rapid increase in storage and the data they store will be massive, so you dare to session stored in the server 7 day?

There are two ways to avoid this situation. First, do not give a session set period of 7 days, but with a cookie to store the 7-day period. Because the cookie is stored in the client, will not cause too much pressure on the server, each time critical data via cookie store, and look through the complete database data, and store it in the session has failed, it becomes up to a the road. Second, you can set the session activation passive, so session after 30 minutes does not eliminate, but to the hard drive will be passive, when the session is used to turn the passive activation file into memory for call . Below, I will explain the two methods in detail by way of example.

3.1 Cookie session with the concomitant health

First, we need to remember a password option:

<input type="checkbox" name="remember" value="rememberMe" checked="checked"/>记住我 

Then get this parameter in the servlet, and after the user name and password are correct in judgment, the account number and password separated by the presence of a cookie with a #, valid for seven days and set, the cookie on the client side, do not worry too much pressure on the server .

String rememberMe = request.getParameter("remember");
if(用户名密码正确){
    if(rememberMe.equals("rememberMe")) {
        Cookie cookie = new Cookie("user",username+"#"+password);
        cookie.setMaxAge(7*24*60*60);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
    }
}

After re-write filter, the first to write notes, and then write the contents: 1. First requset and converted into http response mode, and then get session. 2. determine if the session is not user this property, and to find user the cookie from the cookie, if found, to obtain a user name and password, and then look UserBean objects corresponding with userService the username and password in the database, and store it again to session in the final release.

@WebFilter(filterName="UserFilter",urlPatterns="/client/*",dispatcherTypes= {
        DispatcherType.REQUEST,
        DispatcherType.FORWARD,
        DispatcherType.INCLUDE
})
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)       throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        if(session.getAttribute("user")==null) {
            Cookie[] cookies = request.getCookies();
            Cookie cookie = CookieUtil.findCookieByName(cookies, "user");
            if(cookie!=null) {
                String[] userinfo = cookie.getValue().split("#");
                String username = userinfo[0];
                String password = userinfo[1];
                UserService userService = new UserServiceImpl();
                try {
                    User user = (User)userService.login(username, password);
                    session.setAttribute("user", user);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                
            }
        }
        chain.doFilter(request, response);
    }

Thus, it is through cookie and ingenious collaboration session, and up to seven days to complete an auto-login feature.

3.2 Session passive activation reliance

First, we must realize so, you need to go to the configuration file were born, because although the default session activation is turned on, but passivation is closed. Taking into account as far as possible without affecting the normal use of other tomcat using this project, we only open passivation for the web project. This need to create a context.xml file in / WebRoot / META-INF directory, wrote the following in it:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
        <Store className="org.apache.catalina.session.FileStore" directory="zhangA" />
    </Manager>
</Context>

In this way, it can make tomcat session passivation to the working path zhangA folder does not operate after 1 minute. We can first look for, or write a listener to verify authentication. So I went to work to find a path, and sure enough, there have been at work Catalina localhost under TomCat8.5 \ \ \ \ bookstore called zhangA a file folder, and which is exactly what we have just passivation out session file. Then re-tested under the monitor, first of all let us User achieve HttpSessionActivationListener and Serializable two interfaces. Next, in the output method sessionDidActivate "I was activated" In another approach, the output "I was passivated." Then restart the server, log on to observe output again. A minute later, see the console output "I was passivated", and once again we refresh the page. Before filter for reasons not deleted, the page in the client will detect each run there is no user session this property, so the console output immediately, "I was activated." Thus, the activation of passive test perfect ending.

//部分代码
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;

public class User implements HttpSessionActivationListener,Serializable{
    @Override
    public void sessionDidActivate(HttpSessionEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("我被活化了");
    }
    @Override
    public void sessionWillPassivate(HttpSessionEvent arg0) {
        // TODO Auto-generated method stub
        System.out.println("我被钝化了");
    }
}

At last

I hope this article can help you better understand the session.

Guess you like

Origin www.cnblogs.com/zhangA/p/11072775.html