Spring MVC: Principle and use

Source: Internet
Author: User
Tags log log

I mentioned the Spring injection function in my last blog, so that it is not necessary to generate an object when there is an object dependency (meaning the last blog post), especially when there are more stateless objects, this is especially handy, plus Spring provides Two ways of using XML configuration files and code annotations to make use more flexible. However , Spring's functionality is much more than that,and the power of spring is actually the Java background framework, Spring MVC , it is useful to separate the logic of the background from the visual diagram and to facilitate the use and expansion, especially in large projects.

PS: Sell your own ads, the previous blog, "Spring Injection: Configuration and annotations" (if you see this blog post on other plagiarism sites to find out where the previous blog post is, this will have a more coherent understanding, By the way to spit out these plagiarism site, oneself crawl Other people's blog to put on their own website, do not write a quote from where, this is not very good ~ ~ ~ ~http://blog.csdn.net/u011579138 /article/details/51379066

Mvc

First about what is mvc because he is also slag, So for the convenience of beginners to learn, or to introduce their own understanding of the mvc (not necessarily completely right, for reference only, the veteran can skip this paragraph directly). mvc is a three-something abbreviation, model view Controller

Model: Business model classes, such as: Some classes in the shopping program that contain user information, which have only get and set methods to get the values, or often refer to Serviceis those objects that do not require a specific value, only those classes that make method calls, all of which belong to model. Classes that can be easily understood as handling business logic

View: Views to the user, such as HTML page,js,CSS effect these. Simple comprehension is what the user sees.

Controller Controller, so the description may not be well understood, for example, the browser came up with a request, when the controller ( controller model " return a view after the business model has been processed ( view ) to the user, this is a complete process. There are beginners that may control what the controller does, such as a url It passed a parameter 1 may be requesting a Web page, parameter 2 may be requesting another Web page, This is where the controller is used to give the request to which business processing model.

Just like Courier, the user sends a courier, controller toget The courier, according to the user's request (parameters), to the corresponding region of the courier (model), After processing the sending task, the courier Returns a result (view) to the user, telling the user that I am done. This is a process of MVC.


Spring MVC Principle

is actually based onservleta framework thatservletcan be understood as a Web page with a logical mapping (specifically, please teach yourself),Springis to map all requests to a callDispatcherservletan object to go, and then the request is distributed by this object, a bit similar toControllerthe feeling. DispatcherservletFind aHandler(This is actually done by calling in ahandlermappingsof theListobject to find theHandlerexecutionchain, in thisHandlerexecutionchainIt 's inside .Handlerand theInterceptor, the source details if I have time to write a blog post to discuss the implementation of the source code, because it is too complex, here does not introduce too much. FindHandlerafter that, it will passHandlerFindHandleradapter, here'sHandlerand theHandleradapterthe difference, according to a few blogs I've looked at, says so.:Handlerbe responsible for finding the class that needs to handle this request.Adapteris responsible for finding out which method in this class handles this request(The following two blogs all say this, the second cited example is outdated, theAdapterhave been abandoned by the authorities).

http://www.360doc.com/content/14/1024/23/18637323_419613178.shtml

http://www.mamicode.com/info-detail-877142.html

Here I do not agree with this statement , I will explain later, here to continue to introduce the spring MVC process,dapater found will call The handle method calls the function that handles the request (that is, model). In general, this function returns something that is processed by conver to create an interface (that is , view), When it is generated, it is returned to the user, so that a process is finished. As shown

The real role of Handler and Handleradapter?

But I by looking at the source code, found that it is not like this, in fact, when the handler has determined which specific method to deal with this request. For example, here has actually found the corresponding method,downloadreportfile, so here is not to find the class, and has found the method inside the class, and here is the standard of determining the method is actually to judge the URL and http methods (GET POST).

Second, look at How adapter is, is not really determined the specific method, first paste a few source code (here do not panic, as a beginner worried about looking at codes very annoying or do not understand, slowly calm down, in fact, it is easy to understand, and I will use the detailed language to express, So don't skip this section.)

Here you can see throughGetHandlergot aMappedhandler, in factMappedhandleris aHandlerexecutionchain(can refer to the above paragraph mentioned above, if the text too much can be used in the browserctrl+fFindHandlerexecutionchainthat paragraph). Check it after you find itHandlerand theMappedhandleris not empty, and then throughHandlerGetHandleradapter.


Next layer, look at the principle of gethandleradapter, from handleradapters this container to traverse, if support this handler return the corresponding Handleradapter (Care for Beginners: Logger is used to hit log log of the tool , regardless of the code logic).

And then the next layer, see how the Spports inside is implemented. Can see is to judge the type of handler, and see supportsinternal return results, very simple.

Then the next layer to see how supportsinternal this function, the result of a look, is to return true. So you find that actually getting handleradapter doesn't really have anything to do with the positioning method.


That's why I question what Handleradapter's role is. I asked a supervisor of the company, and found that his own practice of spring itself was not clear, so he did not get the answer to the question.

Here Handleradapter there are 3, the above source code is the first one, but the latter two I also looked at, just check whether it belongs to those types, there is no specific method, that is to say handleradapter there is no way to point to which method, Point to the specific method is inside the handler.

So here's a personal guess, handler is pointing to a specific method,handleraadpter is used to implement the specific method (in the back will see, in fact handleraapter has a Handler method, which is called in this method Handler The method pointed to in the


Handlerintercetptor

Here, by the way, explain the role of Handlerintercetptor, these two interceptors are actually an event trigger mechanism, before handle this request to do something (Applyprehandle in Handlerexecutionchain), Do something after handle this request (Applyposthandle in Handlerexecutionchain), similar to the pipeline mechanism in Netty. That is, spring allows you to do some processing by adding interceptor before or after asking you to process the request.


Handlerexecutionchain

As the name implies is the execution chain, which contains a handlerinterceptor container, the default is two interceptor, and then Prehandle and Posthandle are empty. If you want to implement it, you can add your own interceptor inside. And then there is a handler, which has already been said.

In the figure Mappedhandler is Handlerexecutionchain, call all Inteceptor Prehandle First, and then call adapter's handle function, Call all Interceptor's posthandle again. where if Applyprehandle return false, that is, the event is finished, that is, the function is not required handler to deal with, so this time will be directly return, for example, some parameters are obviously illegal, can be directly not processed, such as

Spring MVC Usage

Understand the concept, and then introduce the usage. I only introduce the use of annotations here, which is more commonly used. Most of the code in Spring MVC is already written, and all you need to do is write business processing.

First intercept the request, with annotations to inject a class, in this class to write methods, with @requestmapping annotations, value is Uri,params is the parameter, you can add a method, to determine whether the HTTP approach is GET or post, The parameters and return types of the body of the function are completely self-defined, with no special formatting. (At first I always do not know why these functions are so many parameters, is not fixed to these, and then read the source found in fact these are made with Java reflection, parameters are not limited to the number of the kind of function declaration method, the return type is object, so these return types and parameters are not fixed). However, you can usually define some of the parameters you need.

The function of the return value

No @responesbody.

Without this annotation, it is important to note that what is returned is used as the identity of the resource invocation, for example, you return a string type of a, which will be resolved by default to find a resource file such as HTML or JS named a. If you want to return other types, you have to look at the spring default branch does not support parsing, it is possible to write their own parsing class, this class is viewresolver, specifically parsing these return objects (see the above flowchart in the fifth step). Of course, the resources here are static, if you need some dynamic parameters, it is necessary to use the Modelmap (the above flowchart also has, the sixth step), is in the viewresolver after processing and then used to modelmap some of the value of the inside of the dynamic processing.



Have @responsebody

If this annotation, it means that the returned object is not used as a resource identifier, but rather as the package body content returned as HTTP. The above is for you to return something, spring to help you parse into a view of the return, this is to return the things you returned directly as content. As the name implies Responsebody. What is returned here is also the need to parse, parse this called Converer, the returned object is parsed into the content can be put into the HTTP package body. Spring supports several returns by default, such as String,json and ByteArray (see the source for details). So if you're going to go back to an object you wrote yourself, write a converer yourself, or you'll end up with no return.

This is the approximate usage, in fact, Spring has many kinds of usage, there are also many supporting things, such as can and other frameworks, such as mybatis or struts, but I have limited ability to study spring a week to reluctantly study these things, In conjunction with other frameworks, there is only a little bit of mybatis-related stuff, and if you have a chance, you have to practice more.

In addition ZZ again mouth a little more, take care of the beginning said. In fact, Spring MVC is also based on Servlets, so it is possible to implement network request processing directly with servlet without spring MVC method. And spring makes a lot of calls to judge that it actually sacrifices some performance. But still people use spring, in fact, large-scale project management and maintenance comparison is more convenient this logic will be more clear, because here will model,view,controller to separate, processing logic and return interface in different places, If the servlet is bound together. This is probably one of the benefits of spring. But the performance aspect of spring should be at a disadvantage.

PS: I am a slag, but each time in the study of a thing will be summed up this framework has what advantages and shortcomings, this is a slag of me to promote a direction, so million hope gentlemen mutual encouragement.

Because the predecessors, can be higher

Spring Source Analysis http://www.360doc.com/content/14/1024/23/18637323_419613178.shtml

PS: This blog is mainly based on ZZ himself to view the source code and reference this blog post, other blog posts also have reference, but not much reference, so here is not listed, but also very grateful to the predecessors left the literature, if forwarded this article, please indicate the source

http://blog.csdn.net/u011579138/article/details/51420185

Spring MVC: Principle and use

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.