Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze Spring MVC framework deeply

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to deeply analyze Spring MVC framework. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

In today's MVC framework, it seems that Webwork2 is gradually becoming mainstream, and the combination of Webwork2+SpringFramework is becoming more and more popular. This seems to mean that the MVC framework that comes with Spring is much worse than Webwork2, so people are using Webwork2 instead. It is true that Spring's MVC framework is not the core component of the entire Spring, but it is more powerful than many people think. Many people, including xiecc, think that Spring's MVC framework is very good, even better than Webwork2.

Here are some important decisions made by Spring's MVC framework at design time, and compare them with relevant MVC framework such as Webwork2 or struts:

One. Spring's entire MVC configuration is based on the IOC container

Compared with struts or webwork2, this is a bit of a strange decision for ms. If you take a look at the configuration file of Spring MVC, you can see that instead of action or form, the configurations under some bean,Bean with specific names are simple or somewhat complex attributes. What we see is the easier data structure of the machine, not the elements that are easier for people to understand.

But this is precisely the root of the power of Spring's MVC! Because its configuration is the configuration of Spring's core IOC container, which means that the power of all IOC containers can be demonstrated here, we can extend and enhance Spring MVC as much as we like, and we can accomplish a lot of unimaginable tasks in other MVC framwork. Do you want to extend the new URL mapping? Do you want to change the implementation of themeResolver or LocalReolver? Want to display a new type of View on the page (such as RDF, hehe, a little secret: xiecc studies the semantic Web, although it doesn't do business, doesn't write papers, but only writes gossip)? Do you even want to define AOP directly in Controller? All this is a piece of cake for Spring's MVC.

I have not carefully studied the extension mechanism of Webwork2. I know that through Webwork2's interceptor mechanism, a lot of extensions can be done, and there is even a simple IOC container. But no matter how powerful it is, how many extension points it provides. Its power is hardly comparable to that of a real IOC container. Struts's plugin function is notoriously abusive, although it also provides a plugin mechanism.

Another reason Spring uses IOC configuration is to make it very easy to integrate Spring's MVC with Spring's IOC container. Spring provides integration with struts and webwork2, but such integration requires indirect packaging, which always feels unnatural. And it will also lead to a concept of multiple configurations, webwork2 needs to configure bean in Spring, and then configure its own xwork file. Imagine, our bean is directly a controller, can directly complete all the tasks of MVC, this is how cool feeling.

Another reason Rod Johnson uses IOC containers to implement is that it reduces a lot of development effort. Take a look at urlMapping. The property it provides is a HashMap in itself. Once the configuration is complete, the data in our bean will naturally exist. Haha, that's cool. You don't have to parse XML like struts and read its contents into HashMap one by one.

Although this configuration will be a little strange, but if we are very familiar with Spring's IOC container, we will find it very friendly and very simple.

* is a simple secret. How does Spring know that the configuration of a bean is urlMapping? Another bean configuration is viewResolver? In fact, it is very simple, read all the bean into memory, and then through the name or type of bean to find it. Finding by name is a simple getBean method, while finding by type uses the static method of BeanFactoryUtils.beansOfTypeIncludingAncestors.

Spring provides clear Model,View concepts and corresponding data structures

There is an interesting data type in Spring called ModelAndView, which simply encapsulates the data to be displayed and the results displayed in a class. But it provides a clear concept of MVC, especially the reinforcement of the concept of model, which makes the logic of the program clearer.

I remember that when I was writing programs in Struts, I often put things into HttpSession or HttpServletRequest (or set to form, although not very useful) in order to display data, which led to the ambiguity of the concept of model and the tight coupling between struts and JSP pages. If we want to replace it with Veloctiy, we have to add another plugin, because there is no need for data not to be put into request in velocity.

Webwork2 emphasizes decoupling from Web framework and the simplicity of its command schema, so there are only simple get or set methods in its action, and if it returns data, it simply returns a String. Such an implementation has its benefits, of course, but it plays down the concepts of model and view. Rod Johnson believes that Action in Webwork2 contains both Action and Model responsibilities, and that such a class has too many responsibilities and is not a good design. Of course, Jason Carreira doesn't quite agree with this view, because the completion of model objects in Action can be delege to other objects. But in any case, the root of this argument lies in the downplaying of the concepts of model, view and even web in Webwork2. The benevolent see benevolence, the wise see wisdom, the result of the * still depends on the individual likes.

Spring's Controller is Singleton or thread-unsafe

Like Struts, Spring's Controller is Singleton, which means that every request comes over, the system will use the original instance to deal with, which leads to two results: we do not have to create Controller each time, reducing the time of object creation and garbage collection; because there is only one Controller instance, when multiple threads call it, the instance variable in it is not thread-safe.

This is where Webwork2 boasts that every Action is thread-safe. Because every time a request comes over, it creates an Action object. Since the efficiency of modern JDK garbage collection is no longer a problem, the pattern of throwing away after creating an object has been recognized by many people. Rod Johnson even uses this as an example to prove that the object pool function provided by J2EE is of little value.

But when people are bragging about how important thread safety is, I would like to ask how many people need to consider thread safety in how many cases? Rod Johnson also raised other problems when analyzing EJB. It is not that the world will end without the thread safety magic of EJB. In most cases, we do not need to consider thread safety at all, nor do we consider object pool. Because we don't need to keep instance in most cases.

At least I wrote so much struts Action and so much Spring Controller that I hardly encountered the problem of keeping the state in the instance variable. Of course, maybe I didn't write enough code. Craig R. McClanahan, the designer of Struts, once said that he had two immature conditions when he designed struts: there was no concept of test-driven development at that time, and JVM's garbage collection performance was too poor at that time. If redesigned now, he would also adopt the design method of generating a new object for each request, which can solve the problem of thread safety.

IV. Spring does not hide Servlet-related elements such as HttpServletRequest or HttpServletResponse like Webwork2 or tapestry

This is another important design decision. We have no HttpServletRequest or HttpServletResponse in Webwork2, only data in getter, setter or ActionContext, which results in a clean Action, an Action that has nothing to do with Web, and a bean that can run independently in any environment. So what does Webwork2's Action based on Command mode bring to us? I think there are two main points:

1. It makes our Action very easy to test.

two。 Users can add business logic to Action and be reused by other classes.

However a closer comparison with Spring shows that the benefits of these two features are not as significant as we thought. Spring's Controller class can also be easily tested. Take a look at the package under spring-mock. It provides MockHttpServletRequest, MockHttpServletResponse, and other classes that make testing Controller extremely easy. Let's take a look at the business logic in Action. Jason Carreira once said that we can add business logic to Webwork2's Action as much as we want, because Action does not depend on Web. But how many people actually add business logic to Action? Most people will give the business logic delegate to another Service class or Manager class. Because we know very well that adding business logic to Action will make the hierarchical architecture of the whole system unclear. Anyway, the Web layer is the Web layer, and the business layer is the business layer. Mixing the logic of the two will always cause problems. And adding business logic to Action will use this Action class to become huge. The Action of Webwork2 is created by each request. Although the performance impact is not great, it does not mean that the business logic has to be re-new every time. In most cases, the business logic should be a singleton.

Of course, not showing request and response to users will also bring a loss of functionality. In general, it may be enough to use the interface provided by webwork2, but sometimes we have to know about request and response in order to be more powerful. For example, one of my previous projects has a page with a tree structure generated dynamically by recursion, which shows that recursion on the jsp page is painful or impossible, so I use response to write the page directly, which is very easy in spring, but it may be more difficult in webwork (I am not sure, I am not deep enough, maybe the master has a way).

Spring provides a good but not sufficient interceptor mechanism

Looking back at struts, it doesn't even give us the opportunity to hook point in the architecture, and we don't have any chance to join our own interceptor. We can only make a limited extension by overloading struts's RequestProcessor class.

When it comes to Webwork2, it seems that interceptor has suddenly become the core of the whole Framework. Except for the core components of Action, everything else is interceptor. Its super interceptor function makes it very convenient for us to extend the entire architecture. Some people call this interceptor AOP,Jason Carreira and proudly claim that it is called pragamtic AOP. I don't agree that this is AOP, it's just a simple interceptor mechanism. But in any case, its interceptor does have powerful features.

Spring also provides its interceptor mechanism, and its HandlerInterceptor three interceptor methods: peHandle, postHandle, afterCompletion. Correspond to before Controller execution, after Controller execution and after page render, respectively. Although it is sufficient in most cases, it is clearly not as powerful as Webwork2 in terms of functionality. From AOP's point of view, it does not provide around interceptor, but only before and after interceptor. This means that we can't keep the state before and after interceptor. In the simplest case, if we want to calculate the execution time of a Controller, we have to hold the state of begintime after executing before, and then call it out in after, but obviously maintaining this state will be a problem, we can't put it in the instance variable, because interceptor is not thread-safe. Perhaps this problem can be solved through ThreadLocal, but such a simple function has to be handled in this way, and it is obvious that there is something wrong with the design of the Interceptor itself.

Spring provides MultiActionController so that it can contain multiple Action in a class

This design is similar to struts's DispatchAction, except that it provides a more flexible mechanism. As our project gets bigger, it's worthwhile to put functionally similar methods in the same Action! Webwork2 lacks such a mechanism. If you look at the source code of Spring, you will find that the workload of implementing MultiActionController is actually quite small, but it is done by using the reflection mechanism to execute the parsed method name. In fact, Webwork2 can also provide such a mechanism. Although it is not very elegant in terms of design, it is really useful.

7. Spring provides more options

Take a look at the Controller provided in Spring, which provides many different Controller classes. Do you want to generate Wizard? Do you want a Controller dedicated to submitting form? Do you want to hold a class with multiple methods? Spring provides a wealth of subclasses to extend these choices. Of course, we can easily expand these functions ourselves.

Take a look at Spring's ViewResolver, which provides countless different types of ViewResolver. More importantly, we customize the way our pages are mapped. Look at strtus, look at webwork2, there will be a layer of indirect conversion between page and forward name, and we have to configure a string (typically success) in the configuration file that corresponds to that page. But we have more freedom in Spring, we can adopt the strategy of webwork2, or we can use a simpler strategy, such as the mapping method of removing the extension of the JSP file name. Some people may think this mapping is naive, but I think it is a very useful way, even in large projects.

Are there any new extensions? Look at Spring Web Flow, which is a subproject of SpringFramework. It provides a configurable implementation for a long list of Wizard pages based on page flow. In Spring 1.3, it will be part of SpringFramework.

Eight. Spring's tag

Although the number of tag in Spring is pitifully small, it is carefully designed. Its goal is simple: to make it easy for artists to edit pages. Because in Spring pages, Text is still Text,checkbox and still CheckBox, unlike Tag in struts or webwork2. It just wraps the input in Springbind. So although there will be more code on the page than Webwork2, it is definitely valuable.

In the next few chapters, I will analyze how Spring allows our Web applications to access the IOC container without knowing ApplicationContext, then conduct a simple source code analysis of the design and implementation of Spring, and then give several ways to extend Spring MVC.

The above is the editor for you to share how to in-depth analysis of Spring MVC framework, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report