Remember when I wrote it spring-session Realize distributed cluster session Share of
When , It's about using filter and HttpServletRequestWrapper You can customize your own getSession method , Implementation of the session Control of , So that session Store in a unified location for storage , achieve session Purpose of sharing . But how to achieve this is not mentioned , Today, we will implement a simple session share .

   What a long long road! , I will search up and down !

  github: <>

   Code cloud (gitee): <>

Decoration mode

   Before we get to the point, let's take a look at another topic , Relax . Although house prices are still high , But still can't stop everyone's desire for a new house and the enthusiasm to buy a house . If you buy a blank room , There is no doubt that there is still a difficult task to face , That is decoration . The renovation of the new house does not change the nature of the house for living , But it can make the house more beautiful , More warm , More practical , More able to meet the needs of home . In software design , We also have a kind of similar new house decoration technology, which can be used for existing objects ( a new house ) To expand the function of ( renovation ), In order to obtain the object which is more in line with the needs of users , Make the object have more powerful function . This technology corresponds to a design pattern called decoration pattern .

   Decorator mode is also known as packaging mode , Expand the function of objects transparently to clients , It allows us to change the underlying code without modifying it , Give our people new responsibilities . Is an alternative to inheritance .

   Decoration pattern class diagram

   Role in decoration mode :    

     Abstract component (Component) role : Give an abstract interface , To standardize the object of receiving additional responsibilities .
     Specific components (ConcreteComponent) role : Define a class that will receive additional responsibilities .
     decorate (Decorator) role : Holding a component (Component) Object , And define an interface consistent with the abstract component interface .
     Specific decoration (ConcreteDecorator) role : Responsible for the component object “ Paste ” Additional responsibilities

   Source code implementation
public interface Component { void sampleOperation(); } View Code
public class ConcreteComponent implements Component { @Override public void
sampleOperation() {// Write specific business code System.out.println(" I am ConcreteComponent"); } }
View Code
public class Decorator implements Component { private Component component;
public Decorator(Component component) { this.component = component; } @Override
public void sampleOperation() { // Delegate to a specific build component.sampleOperation(); } }
View Code
public class ConcreteDecorator extends Decorator{ public
ConcreteDecorator(Component component) {super(component); } @Override public
void sampleOperation() { // Write the relevant business code System.out.println(" call component Business processing before method ");
super.sampleOperation(); // Write the relevant business code System.out.println(" call component Business processing after method ");
} } View Code
     More details can be found in spring-boot-test
Under the com.lee.decorator Package

  jdk Cases in

     Decoration mode in Java The most famous application of language is Java I/O Standard library design . because Java
I/O Libraries require a variety of combinations of a lot of performance , If the performance is implemented by inheritance , Then each combination needs a class , This will result in a large number of classes with repeated performance . And if you use the decoration mode , Then the number of classes will be greatly reduced , Performance duplication can also be minimized , So the decoration pattern is Java
I/O Basic pattern of Library .

     because Java I/O There are so many objects , It's just drawn here InputStream Part of

     Let's take a look at the corresponding roles of this class diagram in decoration mode

       Abstract component (Component) role :InputStream, This is an abstract class , Provide a unified interface for each sub type
       Specific components (ConcreteComponent) role :FileInputStream, The interface defined by abstract component role is implemented
       decorate (Decorator) role :FilterInputStream, It's done InputStream Specified interface
       Specific decoration (ConcreteDecorator) role :BufferedInputStream

custom session Administration

   Let's take a look at the start to response sequence diagram of a request

  Interceptor Rely on specific framework ( Of course, we can do it ourselves ), no Servlet Content of , Let's put it aside for now , That's equivalent to the request going through first Filter chain , Again Servlet, then servlet After processing , Go through again Filter Chain back to browser .

   At this point, we need to session For customization , What can we do about it ? Two options , One is from Servlet start with , Second, from the Filter start with . Let's think about it , from Servlet Is it feasible to start with ? feasible , It's just that the feasibility is very low , Because there are so many things we need to customize , The set of containers Servlet We all need to implement the specification ourselves . If Filter start with , We can continue with the container implementation , And insert our custom content from it , So there are very few changes . How to realize it , Let's look down

   customized session Administration

    servlet Containerized session establish

       In the realization of our own session Before management , Let's have a look first session stay servlet Create in container .

       Client first request request.getSession() Time , That is to say, the server calls for the first time in the client's request request.getSession() Time , The server will be created Session Object and save in servlet Containerized session In the set , Generate one at the same time Session
id, And through the Set-Cookie command , Send request settings to client cookie Response to (cookie Set in Session
id information ), After the client receives the response , A JSESSIONID=XXXXXXX Of cookie information ; Next, every time the client sends a request to the server , The request header will carry the cookie information ( contain Session
id), Then every request from servlet Containerized session For the client in the collection session 了 , This is equivalent to maintaining the interaction between the user and the server .     

       be careful :
         First request request.getSession() Time , The head of the request is not with you session id Information for , The response header contains settings session
id Of cookie set command ; After that, the client's request ( No matter when the server calls request.getSession()), There are all request headers session
id information , The response header will no longer be set session id Of cookie set command
        session as well as session id On the first call request.getSession() Created when (session Another comment on overdue , Not the content of this article )

         Different containers session id The name may be different ,JSESSIONID yes tomcat in session id Default name for

     custom session Creation and acquisition of

       Does not rely on any framework , Just use it Filter +
HttpServletRequestWrapper Realize our own simplicity session Administration . custom Filter The role of the Servlet before , We will HttpServletRequest Packaged into our own HttpServletRequestWrapper Class implementation :CustomizeSessionHttpServletRequest, Then arrive Servlet Of HttpServletRequest The object is actually CustomizeSessionHttpServletRequest; We rewrite it CustomizeSessionHttpServletRequest Of getSession method , Make it from our own session Container , So as to achieve session Custom management of . In order to achieve the effect of the same session , In creating session When , Need to go response Add cookie, preservation session
id, The next time you ask , The browser will cookie The message is coming , Let's go cookie In the session id, according to session
id take session Container acquisition session, This will ensure the same conversation effect .

       The specific code is not posted here , Check it out customize-session
, The effect is as follows

       Visit first http://localhost:8083/customize-session/test, At this time, there is no production session Of ,http://localhost:8083/customize-session/ The request is index.jsp,jsp Built in object requested session, At this time session, And let the browser set the cache , Then every request after that will carry the session
id Cache for .

     Key part class diagram


      ServletRequestWrapper There are member variables in ServletRequest request;

     Decoration mode role correspondence

       It's not a decorative pattern in the strict sense

       Abstract component (Component) role :ServletRequest
       Specific components (ConcreteComponent) role : nothing
       decorate (Decorator) role :ServletRequestWrapper
       Specific decoration (ConcreteDecorator) role :CustomizeHttpServletRequest


  1, Decoration mode

     The decorative pattern in the article is not very detailed , If you have anything you don't understand, you can go to the two books I refer to for more detailed information .

    jdk Source code ,I/O Decoration pattern and adapter pattern are widely used in standard library , Interested partners can go to see in detail .

  2, custom session Administration

    Filter Intercept request , take HttpServletRequest Packaged into our own CustomizeSessionHttpServletRequest, And then insert our session Creation and acquisition logic , because session The method of obtaining is often :request.getSession();

     to response Add cookie, Need to be in response Before submission , Otherwise, the addition is invalid ;

     In addition, we have customized it HttpSession:CustomizeSession, It's about better control session

  3, Insufficient

     First of all, I want to emphasize one point : The direction and thinking are right !

     At present, it's only realized session Creation and acquisition of , The implementation is quite general , There is a lot of room for improvement ;session Management also includes :session be overdue ,session Refresh, etc ; in addition session The storage of is dead in this article , There is no external submission interface to implement multi-mode storage , A good way is to provide interfaces and default implementations .

  4, objective

     The purpose of this article is to let you customize session There is a simple understanding of management , If the shiro Of session Administration , perhaps spring-session Of session Management entrance , We may not know how to read , After all, these two systems are mature , There are a lot of things involved , We may be deterred ; But anyway , The implementation is the same , just shiro,spring-session On this basis, various contents are enriched , Make the system more mature .

     For another post of mine <> Get ready

reference resources

  《Head First Design patterns 》

  《Java And pattern 》