Don't be afraid, take your hand and rip, pull, tear down Springmvc's coat

Source: Internet
Author: User

Refers to the framework, we have to mention the source, we always want to ask the big God to fly us, but see the source is a great God learning the most direct way, but every time we summon up the courage to look at the source code is like this
But a bit of open source code, immediately after the flood of codes, your heart may be like this
So I'm not afraid to look at the source code, a picture of the mapper principle of MyBatis the time also mentioned, MyBatis source relative to other frameworks is relatively simple, more suitable for the beginning to overcome fear to see the source of actual combat, due to Struts2 shortly before the security issue, So Java development, the performance layer framework is basically SPRINGMVC, then we will tear, pull, tear down the mystery of SPRINGMVC, can be compared before fear, STRUTS2 implementation process is not so difficult, this article will involve some Struts2, Javaweb and Springmvc use some of your details.
This is one of the most classic Springmvc execution flowchart, I believe that Java development has seen, of which there are three core places, respectively, are handlermapping, Handleradapter, Httpmessageconveter. After reading this figure after bigger picture, will drive, the front high energy, please hold firmly sit well.
Look at the source, the first to find the entrance, then where is the entrance? From the flowchart we can see that Dispatcherservlet is the Portal core class (in fact, from the SPRINGMVC configuration file can also be learned), but there are so many methods, we know which method is the portal? Let's take a look at the succession diagram of Dispatcherservlet.
As can be seen from here, the essence of Dispatcherservlet is the servlet, so we recall the life cycle of the servlet, the main three methods in the life cycle are void init (servletconfig config), void Service (ServletRequest req, servletresponse res), void Destroy (), but we found that there was no service at all in Dispatcherservlet, So this is the time to find the parent class Frameworkservlet. So we hit a breakpoint in the service method and started the request,. Super.service (request, response);

This will call the corresponding method (Doget or Dopost) based on the requested type, for example, we have a GET request for this test, so we call doget.
Dodispatch, from the literal understanding that this method is to distribute the request, the core logic is here
Checkmultipart This method is to check whether it is a binary request (File upload request)

Protected HttpServletRequest Checkmultipart (HttpServletRequest request) throws Multipartexception {// Multipartresolver This is a view resolver, so here's a look at whether there is a view parser, and if request is not a binary requested if (this.multipartresolver! = null && This.multipartResolver.isMultipart (Request)) {if (Webutils.getnativerequest (Request), MULTIPARTHTTPSERVLETREQUEST.CLASS)! = null) {Logger.debug ("Request is already a multiparthttpservletrequest-if not in a Forward, "+" this typically results from a additional multipartfilter in Web. ");} else if (Request.getattribute (webutils.error_exception_attribute) instanceof multipartexception) {logger.debug (" Multipart resolution failed for current request before-"+" skipping re-resolution for undisturbed error Rendering ");} else {//If it is binary, wrap the request in a layer and return multiparthttpservletrequest return This.multipartResolver.resolveMultipart ( request); }}//If not returned Before:return original request. return request;}
Because it is not a binary request, it returns the original object, so multipartrequestparsed = (processedrequest! = Request); The result is false

Here comes the climax Mappedhandler = GetHandler (processedrequest);
From the word handlerexecutionchain know that this is the process of execution chain
Handlermapping
Handlermapping is the request processing Mapper, it can choose the most appropriate handle (its own controller) according to different requests, the request processing Mapper can configure multiple, who first match who executed,
So what's this for...in it's traversing? In fact, this is already configured in the Dispatcherservlet file.
In fact, this is the packaging of different mapping to judge is through the beannameurl way or annotation way to configure, then what is the Beannameurl way? is what we usually configure in the XML file
Through this, the request is passed into the handlerexecutionchain.
Handlerexecutionchain handler = Hm.gethandler (request);
Handlerexecutionchain
Handlerexecutionchain (processing execution chain) contains two parts, part of the request of the corresponding controller, part of the interceptor, before the actual execution of handle, there are a series of operations, such as data conversion, formatting, data validation These are done by the interceptor
It is also important to note that if you customize n interceptors, you will find that Handlerexecutionchain will have n+1 interceptors, stating that one is inside of him, from which we can know the order of execution, for example, to execute the interceptor first, then execute our controller, So this thing is called Process execution chain
Next came the second wave of orgasm (this time those who say no classmate, the body is still very honest to continue to look down), handleradapter ha = Gethandleradapter (Mappedhandler.gethandler ());
Handleradapter
Handleradapter (processing adapter) This translates into Chinese may be relatively low, but from the name we can be informed that this is used to execute the handler (Controller), what is this for...in in the loop? Actually, this is also configured in the configuration file.
Here is the judge handle suitable for this requestmappinghandleadapter, fit on the return
if (Ha.supports (handler)) {
return ha;
}
Then go down.
String method = Request.getmethod ();
This method is to get the method type, then what is the difference between this get and POST request? A GET request has a cache, but the POST request is not available
Then go down.
if (!mappedhandler.applyprehandle (processedrequest, response)) {
Return
}
Here we can recall the three methods of Handlerinterceptor
public class Myinterceptor implements Handlerinterceptor {
Represents a method that is called before the Controller method executes, returns a Boolean, if true, to indicate the release, or false, to intercept public boolean prehandle (httpservletrequest HttpServletRequest, HttpServletResponse httpservletresponse, Object o) throws Exception {System.out.println (" Myinterceptor.prehandle "); return true;} After the controller finishes executing the method, the view is combined before public void Posthandle (HttpServletRequest httpservletrequest, HttpServletResponse HttpServletResponse, Object O, Modelandview modelandview) throws Exception {System.out.println (" Myinterceptor.posthandle ");} The method that is called after the view is combined is completed public void aftercompletion (HttpServletRequest httpservletrequest, HttpServletResponse HttpServletResponse, Object O, Exception e) throws Exception {System.out.println ("myinterceptor.aftercompletion");}
}
Here is the main traversal interceptor, if the return is false, from!mappedhandler.applyprehandle (processedrequest, response this judgment can be learned, it will no longer continue to execute.
Go on, down.
Actually invoke the handler.
MV = Ha.handle (Processedrequest, Response,mappedhandler.gethandler ());br/> from the comments, here to call the handle method, this method will do a lot of things, For example, the previously mentioned parameter auto-injection is done in this step, this step hierarchy is too deep, the space is limited, temporarily do not discuss, this time the breakpoint hit the method of the controller
@RequestMapping ("/test")
Model.addattribute ("msg", "Hello Toby");
return "Hello";
}
And go on.
Default view name
Applydefaultviewname (Request, MV);br/> What's the use of this default view name? Do we have a situation where we have a direct return model but no view, for example
@RequestMapping ("/value2")
Error: Circular view path [value2]: would dispatch back to the current handler URL [/value2] Again
At this point the method only model, no view, SPRINGMVC will default to you view, the default view name is: Requested name (/value2)
It's the equivalent of re-requesting/value2.
return new User ("Toby", "24");
}
Keep going down Mappedhandler.applyposthandle (processedrequest, response, MV);
From here we know that the order of execution is reversed (this conclusion is first noted, I will draw a picture to awaken your memory)
Go on, down.
Processdispatchresult (processedrequest, Response, Mappedhandler, MV, dispatchexception);
This determines whether to forward or redirect, or to become a different view.
View.render (Mv.getmodelinternal (), request, response);
In this way, the request path is passed in.
Protected RequestDispatcher Getrequestdispatcher (httpservletrequest request, String path) {
return Request.getrequestdispatcher (path);
}
First get the RequestDispatcher object, and finally call forward, in fact, the bottom or servlet content
Rd.forward (request, response);
Go on, down.
Mappedhandler.triggeraftercompletion (request, response, NULL);
OK, by Applyprehandle, Applyposthandle, Triggeraftercompletion, these three methods can learn the order of the interceptor execution, below I use a picture to describe
Write at the end
Springmvc Simple execution process Here is basically finished, but the essence of SPRINGMVC design is not just what we see, every detail is worth our thinking, but the process of thinking is to see the value of the source. For a simple example, take an asynchronous callback, iOS is usually through block, Android is through interface, JavaScript is through function, and then they have what similarities and differences, take node. js, Everywhere is asynchronous programming, but asynchronous set async and very prone to problems, How do we solve the problem of asynchronous synchronization? If it's iOS, how do we do it? These are very worthwhile to think about.
If you also want to get a high salary in the IT industry, you can take part in our training camp course, choose the most suitable course for your study, technical Daniel Pro, 7 months later, enter the famous enterprises get high salary. Our curriculum includes: Java Engineering, high performance and distributed, high performance, in Layman's. High architecture. Performance tuning, Spring,mybatis,netty source analysis and big data, and many other points of knowledge. If you want to get a high salary, want to learn, want to have a good job prospects, want to compete with others can get advantage, want to go to Ali interview but worry about interview but, you can come, group number: 454377428
Note: Dabigatran requirements
1, with 1-5 of working experience, in the face of the current popular technology do not know where to start, the need to break through the technical bottleneck can be added.
2, in the company for a long time, have a very comfortable, but job-hopping interview wall. Need to study in a short period of time, job-hopping to get a high salary can add.
3, if there is no work experience, but the foundation is very solid, on the Java work mechanism, common design ideas, Common Java Development Framework Master Proficiency, you can add.
4, feel that they are very cow B, the general needs can be done. However, the knowledge points are not systematized, it is difficult to continue the breakthrough in the technical field can add.
5. Ali Java senior Daniel Live to explain the knowledge points, share knowledge, many years of work experience combing and summary, with everyone comprehensive, scientific to establish their own technical system and technical knowledge!
6. Trumpet or small white and other groups are not given, thank you.
The target is already there, see the action below! Remember: learning is always their own business, you do not learn time is not much, you learn sometimes can use their knowledge to exchange more free good time! Time is the basic part of life, but also the fundamental yardstick of the existence of all things, our time where our life is there! Our value will also be there to ascend or eliminate! Java programmer, come on.

Don't be afraid, take your hand and rip, pull, tear down Springmvc's coat

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.