Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts
Thursday, January 28, 2010
Spring 3.0 and <mvc:annotation-driven />
I have used Struts1 and Struts2 extensively for years. With that background, I can appreciate some of the things that Spring-MVC brings to the table such as Dependency Injection, clean integration with Bean Validator (JSR-303), smooth Integration with different View Technologies, among others. Furthermore, Spring-MVC has been making improvements through out each release that has made it a more robust framework, including the latest REST support. Like every framework, there is always a "gotcha" in a feature and such is the case for <mvc:annotation-driven /> .
<mvc:annotation-driven /> is a nice feature, however depending on how you are used to organize your Spring-MVC files, it can prove to be confusing. I'll try to explain my findings as clear as I can.
Friday, September 26, 2008
The Domain Model and Struts 2.x
A couple of months ago I had a new requirement where I had to display the look (ui) of only a few of my components in my Struts 2.x application. Specifically, I had to display some dates as date-time while others had to remain the same. I started to hold down for a minute and decided to think how best to tackle the problem. I hate to touch a lot of code for no reason and as many know, changing the domain model code is typically not a good idea.
Struts2 MVC and Converters
In the good old days of Struts 1.x, one would have to register a special Converter object and register it so that BeanUtils can use it when ActionForms are populate via the ActionServlet (wao, I can't believe I had to learn all that). This was a good way to provide good conversion across all your application, however this approach forces the Converter to be applied in all objects of the same type.
As an MVC implementation, the controller should be able to have a way to know what conversion process to use in each action mapping processing session. Struts 2.x provides a way to do this in a clean way with the use of the StrutsTypeConverter class. After creating your own converter class, you can register your converter globally (in a file that must be named xwork-conversion.properties). Alternatively, you can create a-conversion.properties file at the same package level where your model object resides and now you can have custom conversion per property. The latter approach is a powerful feature as it allows you to define a properties file with key,value pair listings. Each key represents the name of the java property of the model object and its value is the fully qualified converter class name. This approach for conversion is very appealing for the following reasons:
Struts2 MVC and Converters
In the good old days of Struts 1.x, one would have to register a special Converter object and register it so that BeanUtils can use it when ActionForms are populate via the ActionServlet (wao, I can't believe I had to learn all that). This was a good way to provide good conversion across all your application, however this approach forces the Converter to be applied in all objects of the same type.
As an MVC implementation, the controller should be able to have a way to know what conversion process to use in each action mapping processing session. Struts 2.x provides a way to do this in a clean way with the use of the StrutsTypeConverter class. After creating your own converter class, you can register your converter globally (in a file that must be named xwork-conversion.properties). Alternatively, you can create a
- Does not mix Struts2 code with Domain Object model code (not even annotations), thus offering a non-intrusive approach to the rendering of the object.
- It encourages a development environment where this file can be generated, overriden or even replaced at build time. This scenario is very appealing for companies that do customizations of a product thus encouraging a "configuration management" approach in the presentation tier.
- It allows you to provide a different converter per property, leaving the model type unchanged.
I was able to successfully display each property as needed and progressively move each component that was required.
Wednesday, September 24, 2008
Powered by Struts 2.x
After working with Struts 2.x for some months now, I feel more comfortable in commenting on some of the features that I feel have been helping me as well as some others that I feel needs some attention. In writing these, I hope that I may be able to learn some from those who may wish to attempt correcting me.
Overall Configuration
The basic file needed is one named "struts.xml". Properties (constants) can be overridden using a struts.properties files. This file takes priority and this is an interesting approach and this seems to mixed well with Maven environments (as well as Ant, of course). You can modularize your application including files of the same type (same DTD) as struts.xml. The one thing I don't understand is the use of DTD over XSD. Not exactly sure why they haven't adopted XSD as the latter are simply more powerful.
Rendering Engine
The fact that you don't need to JSP for your views has been a significant change for me. I know that you can avoid using JSPs using Struts 1.x but the amount of code (and configuration) could be very tedious. With Struts 2.x support for Velocity and Freemarker are already built-in. I've been using the latter for sometime now and I simply love it.
Now, if you consider the "hype" that OSGI is bringing to the JEE world, a templating engine technology (e.g. Velocity, Freemarker) over JSP technology is more appealing as this will allow OSGI environments to resolve proper templates based on the OSGI headers (within each jar). Struts 2.x comes with bundled with a set of predefined templates that the classloader picks from, thus encouraging this pattern (but not demanding it). I see this as a strategic architectural choice which ought to be observed when considering OSGI powered applications.
Servlet Technology and Controllers
Struts 2.x uses Servlet filters (instead of Servlets) as the driving force of the application. This can be good and bad for several reasons. I have found it to be good thus far. Filters can give you the feeling that "intercepting" a controller is simpler (filtering the request). Struts 2.x has default interceptors for different things such as those that parses the parameters and placed them into the value stack, double token submissions, etc. You can always implement your own.
You have a clear option of which interceptors to use and their ordering. This is a powerful feature that if misused can prove a big problem. I recently found a bug on the way I had configured our interceptors. You can do nesting of interceptors so I was repeating the same interceptor multiple times thus doubling my round-trips to the database. Implementing your own is very trivial.
Additionally, Struts 2.x advertise thread-safety POJOs as your actions (Struts 1.x should remember that this issue can make you rely heavily on request/session attributes). I have found that the nature of making this action objects thread-safe are by virtue of having a "request" scope. Since you have an option to use Spring for dependency injection, you configure/annotated your POJOs with scope "session" and block this behavior. I've found this a problem in some cases. I'm still investigating this issue, but does bring something to the table. You can effectively perform IoC in the way Action (controllers) are used as part of your MVC.
IDE Tooling - The good, the bad and the ugly!
As most fairly new frameworks tooling is what helps the adoption of a framework. Struts 2.x lacks this component very much as there are not that many IDEs with out-of-the-box support for Struts 2.x. As of the today, there are few who show some promise, none of which I would recommend investing (yet!). I am a fan of Eclipse, and I have to say that the WTP project works just fine with Struts 2.x and developing with it has been a breeze. Configuring struts 2.x within eclipse is somewhat trivial and I expect IDE plugins to simply help with XML editing.
I have spent a lot of time reading the struts-core source code and I simply like it. I think its a good practice for any developer trying to understand the framework and I'm sure you'll find it very readable, well commented with few problems (although I'm sure there are some). Overall, my experience with Struts 2.x has been very pleasant and I have good reasons to recommend it as a choice for development of new enterprise applications.
Wednesday, September 26, 2007
A Review of the MVC pattern
Tight coupling among software components is one of the common problems in large enterprise applications. This is due to the large amount of data and the way in which this data is represented to users of the application. In practice, it's very easy to fall into the problem of writing unorganized code that, although it delivers a product, it does not maintain any known convention or standard. This only contributes to the problem of extending application functionality (scalability) which is almost certain to happen. Many design patterns are used in the industry to solve different business problems. Among these, the Model-View-Controller (MVC) pattern is one that if often misquoted and misused. In using the Struts Framework for building web-based applications, it is crucial that every developer understand this pattern.
Figure 2 - Struts implementation of the MVC pattern.
In the MVC patterns, a clear distinction is made between three different components. These are the Controller, the View and the Model. Each of this components help segregate and centralize certain functionality of our code away from each other (loose coupling), thus scalability and re-usability is feasible. The following figure provides a small representation of how this components are meant to interact:
In this pattern, the Model component is a representation of some business data. This is also known as "domain model" and is specific to a business. It can also serve as a representation of a "real-world" process that the application is identifying or hold the state of a business entity. The View component is a specific display of the model component in the user interface (UI). This is also known as the "presentation layer" of the application. Thus, if the model component is a
Changes to the model component (information holding business data) are handled through the Controller of the application. This means that if the view component has a function (e.g a button, or a drop-down) that needs to be triggered in order to execute an update on the model component, the view communicates this event to the controller component who executes this change and updates the model component. This level of redirection ensures the controller to handle the proper action per view according to business needs. For example, a bank account number may need to be "read-only" to customers but to staff members, this may be an editable field. In this case, it is up to the controller to decide whether the action of updating the account number should trigger an update operation on the model component and is up to the view component to determine if this functionality is even displayed to the user.
In the context of the Struts Framework, the MVC pattern can be represented using the following diagram. Note that the three components of this pattern appear in the same order as in Figure 1:
BankAccount object, the view component may be an HTML page containing account balance and transactions, or a frame of UI widgets representing the account holder personal information. Note that for both of this examples, the model knows nothing about the view, however the view needs to know some about the model component in order to display it. This direction in dependency is an important concept in this paradigm which encourages loose coupling among components: Developers programming in the model component do not depend on the presentation layer.Changes to the model component (information holding business data) are handled through the Controller of the application. This means that if the view component has a function (e.g a button, or a drop-down) that needs to be triggered in order to execute an update on the model component, the view communicates this event to the controller component who executes this change and updates the model component. This level of redirection ensures the controller to handle the proper action per view according to business needs. For example, a bank account number may need to be "read-only" to customers but to staff members, this may be an editable field. In this case, it is up to the controller to decide whether the action of updating the account number should trigger an update operation on the model component and is up to the view component to determine if this functionality is even displayed to the user.
In the context of the Struts Framework, the MVC pattern can be represented using the following diagram. Note that the three components of this pattern appear in the same order as in Figure 1:
Figure 2 - Struts implementation of the MVC pattern.Struts is focused on web-based Enterprise Applications and is heavily based on Servlet Technology. At the core of the controller component is the
Struts also provides different tag libraries to help in the rendering of the model components in the presentation layer (view), however, it is left to the developers to decide how to display the data by virtue of the MVC pattern. This means that JSP, velocity or any other rendering engine can be used as part of the presentation layer. As for the model this can be any representation of the domain model of the application such as an entity bean EJB, a Java Bean using Hibernate (Session in View) or Data transfer objects to partially represent a domain model object. Other components can also be plugged to controller component such as resource bundle configuration, menu capabilities, tiles, etc. This pluggable architecture mixed with other configurable features (e.g. validation) has made Struts a preferable option when choosing to use the MVC pattern as part of the architecture of a Java Enterprise Application.
Loose coupling between components is the key concept. Different frameworks are available in the open source community, among which some offer an MVC architecture for Java Enterprise applications, however keep in mind that, as quoted in Martin Fowler's "Patterns of Enterprise Application Architecture":ActionServlet object. In general, this servlet forwards control to Action objects (to perform CRUD operations on the model component) or to another view component. This ActionServlet knows how to associate view components with specific Action objects through one or more XML files loaded during the servlet initialization process - init() method. Thus changes to this XML file typically represent a reload of this ActionServlet. In this approach, developers are left to insert code in the Action objects of their choice in order to perform changes in the component. When objects need to be placed in the presentation layer, the controller also uses this Action objects to place this model in proper scope (page, request, session, etc).Struts also provides different tag libraries to help in the rendering of the model components in the presentation layer (view), however, it is left to the developers to decide how to display the data by virtue of the MVC pattern. This means that JSP, velocity or any other rendering engine can be used as part of the presentation layer. As for the model this can be any representation of the domain model of the application such as an entity bean EJB, a Java Bean using Hibernate (Session in View) or Data transfer objects to partially represent a domain model object. Other components can also be plugged to controller component such as resource bundle configuration, menu capabilities, tiles, etc. This pluggable architecture mixed with other configurable features (e.g. validation) has made Struts a preferable option when choosing to use the MVC pattern as part of the architecture of a Java Enterprise Application.
"The value of MVC lies in its two separation. Of these the separation of
presentation and model is one of the most important design principles in
software, and the only time you shouldn't follow it is in very simple
systems..." (page 332)
So, keep these in mind when using Struts. Additional features offered by the framework should not be confused with the objective for which Struts was designed. Overuse and/or additional design without careful planning can prove to reduce scalability thus reducing the value of the product in the long run.
Saturday, September 15, 2007
Introduction to Struts 1.x
Some years ago, I was asked to add a new feature to an existing struts-based application. The feature would include some form validation, form pre-population as well as some embedded logic depending on the authenticated user. Double submissions were also a big concern and had to be detected and avoided. These, among others, are many of the tasks where Struts can be extremely helpful. Sure, there are many things that experienced developers will find as shortcomings (just as any other tool has weaknesses), yet Struts continues to grow from these and is now a well-defined Java Framework for building Enterprise Applications using a Model-View-Controller (MVC) architecture.
One thing to remember is that Struts is not the only solution, is only one of the many. Specifically, it's one commercially popular in the Java programming language. There are other solutions available such as WebWork (now merged with Struts to make Struts2), Spring MVC, Swing, JSF (which is now the official MVC specification from Sun MicroSystems), Stripes, JFace, OpenBravo, etc. Alternatively, other programming languages (such as Ruby on Rails) have an MVC approach of their own. In general, it is the pattern (MVC), not the tool (Struts), that we must remember brings success to an Enterprise Application.
If you are a newbie, be aware that Struts is now branched in two different projects: Struts1 and Struts2. The first one aims to continue development on the original Struts Framework. Struts2 is the new approach for MVC development as developers from the Struts and WebWork2 (OpenSymphony) communities joined forces to provide a cleaner (and simpler) way of developing web-based applications. You may want to consider choosing one first (as suggested on their official site) if you have never used either version as both bring to the table fundamental differences. Unfortunately, as a newbie you are going to need to have some understanding of basic technologies. Although the Struts documentation suggests some of these, I would list the following as the key technologies to understand:
Before Struts, your would have to extract each parameter of a request using a "getParameter()" method of the
In my experience, learning about the Model-View-Controller pattern is the key to using Struts successfully. This understanding, coupled with adherence to good and useful programming practices (which I plan to address in a different blog entry) will help you appreciate Struts better. So read about this and other practices and use this framework to do what is meant to do: "...to create/help web applications utilize an MVC architecture" (Reference)
One thing to remember is that Struts is not the only solution, is only one of the many. Specifically, it's one commercially popular in the Java programming language. There are other solutions available such as WebWork (now merged with Struts to make Struts2), Spring MVC, Swing, JSF (which is now the official MVC specification from Sun MicroSystems), Stripes, JFace, OpenBravo, etc. Alternatively, other programming languages (such as Ruby on Rails) have an MVC approach of their own. In general, it is the pattern (MVC), not the tool (Struts), that we must remember brings success to an Enterprise Application.
If you are a newbie, be aware that Struts is now branched in two different projects: Struts1 and Struts2. The first one aims to continue development on the original Struts Framework. Struts2 is the new approach for MVC development as developers from the Struts and WebWork2 (OpenSymphony) communities joined forces to provide a cleaner (and simpler) way of developing web-based applications. You may want to consider choosing one first (as suggested on their official site) if you have never used either version as both bring to the table fundamental differences. Unfortunately, as a newbie you are going to need to have some understanding of basic technologies. Although the Struts documentation suggests some of these, I would list the following as the key technologies to understand:
- HTTP Request/Response Cycles
- Properties Files and Resource Bundles
- Servlets, Filters, and Web Containers (e.g. Tomcat, Resin, Weblogic, WebSphere)
- Java Server Pages Technology (JSPs, Tags)
- XML
- Model-View-Controller Pattern
ActionServlet Servlet object in the org.apache.struts.action package can prove to be a very insightful experience... Enjoy!Before Struts, your would have to extract each parameter of a request using a "getParameter()" method of the
ServletRequest object. Struts encapsulates this with their ActionForm object, thus learning the life cycle of this class is essential when dealing with incoming HTTP requests. Also, prior to Struts, you would also have to write certain logic to learn how to forward a request to another Servlet for further processing. Struts solves this with their ActionServlet and one or more XML configuration files that drive the application flow. Double submissions of HTML Forms were handled by some hack in between Servlet calls. Struts solves this problem by using a "token-per-request" approach and the methods isTokenValid(), resetToken() and saveToken(). In general, Struts provides an Object Oriented API which helps visualize these problems and many more as objects.In my experience, learning about the Model-View-Controller pattern is the key to using Struts successfully. This understanding, coupled with adherence to good and useful programming practices (which I plan to address in a different blog entry) will help you appreciate Struts better. So read about this and other practices and use this framework to do what is meant to do: "...to create/help web applications utilize an MVC architecture" (Reference)
Subscribe to:
Posts (Atom)
