Comparison between Ruby on Rails and J2EE

Source: Internet
Author: User
Reprinted: http://www.5itjob.net/html/86/86_itemid_1183.html


Ruby on Rails is a relatively new web application.ProgramFramework, built on the ruby language. It is promoted as an alternative to the existing enterprise framework, and its goal, in short, is to make life, at least web development, easier. In this article, Aaron rustad compares some key architecture features of rails and traditional J2EE frameworks.








Ruby on Rails is a Web application framework designed to provide an easy path for application development. In fact, framework supporters claim that Ruby on Rails developers are 10 times more productive than traditional J2EE frameworks. (Read the article "rolling with Ruby on Rails" for more information about this declaration. See references ). Although this sentence causes rails and J2EECommunityThere is a lot of controversy, but the debate seldom talks about how to compare rails and J2EE architectures. This document compares the rails framework with typical J2EE implementations by using common open-source tools in enterprise applications.



What is Ruby on Rails?
To find a simple description of rails in one sentence, you only need to view the project's homepage:


Rails is a full-stack, open-source Web framework written in Ruby. It can be used to easily compile practical applications.CodeIt also has less code than most frameworks spend on processing XML.


Although I cannot guarantee that the framework will indeed provide the ease and happiness it promises, the above sentence really summarizes the quality of rails. The full stack includes web servers, HTTP request processing and response frameworks, and convenient persistent data storage to relationships.Database. By eliminating complex xml configuration files and using the dynamic nature of the Ruby language, rails helps minimize many of the common repeated code in a static type language, making development easier.



Rails and typical J2EE Web Stack
Figure 1 compares the rails stack with the typical J2EE Web stack (including the Tomcat servlet container, Struts web application framework, and Hibernate Persistence framework ).



Figure 1. Comparison between rails and J2EE stacks






 



As you can see, the basic difference between the rails stack and components that constitute common J2EE-based Web applications is very small. Both of them are used to execute application code containers. They both help to separate the application model, view, and control MVC framework, as well as the persistent data storage mechanism.





MVC Framework
Model-View-controller (MVC) is a design mode with a long application time and wide application scope. It originated from smalltalk. Today, almost all gui frameworks, including web and fat clients, are based on this framework. MVC has three parts:Model, Responsible for the business logic, including the application status and the actions that will be executed in this status;ViewUsed to render and present models to users (in Web applications, views are generally rendered as HTML );ControllerDefines the behavior of an application. For more information about the MVC mode, see references.


Front-end Controller
StrutsActionservletAnd railsDispatchservletThey are examples of front-end controller mode. Therefore, they provide the same functions. They accept HTTP requests, parse URLs, and forward request processing to appropriate actions. In struts, actions are extended fromActionFor rails, the action is extended fromActioncontroller. The main difference between the two front-end controllers is how they decide the action to process specific requests.



When using struts, developers need to externalize the ing of specific requests to the xml configuration file.ActionClass. When the first loadActionservletIt will parse the file and prepare to accept the request. According to the Conventions. DoThe end request is redirectedActionservlet, Assigned by actionservlet to the appropriateAction. XML in Figure 2 is a typical ing. It tellsActionservletCallDeleteorder. DoForward requestsControllers. Order. deleteorderactionFor further processing.



Rails adopts different methods. It does not rely on the configuration file to map requests to an action, but discovers appropriate actions based on the request URL. As shown in figure 2, the URLHttp: // localhost/order/delete/4Tell rails to callOrdercontrollerOn the instanceDeleteMethod, and4As an available instance variable. Rails is smart enough to know/OrderMaps to a controller class defined in the order_controller.rb file. If you defineFindMethod, you only need to useFindReplaceDeleteYou can call this method.



Figure 2. url ing between rails and struts






 



Action and Model
In rails and struts, actions act as a bridge between front-end controllers and models. Developers provide the reality of actions to provide application-specific request processing. The front-end Controller is responsible for receiving requests and passing requests to specific actions. Figure 3 demonstrates the basic action hierarchies of rails and struts.



Figure 3. Action hierarchies of rails and struts






 





Is the action a model or a controller?
ActionAndActioncontrollerTechnically, it is part of the controller of the MVC mode because they respond to events initiated by the customer. However, in small applications, developers usually encode the domain or business logic in these classes, so in these cases, they can also be seen as part of the model. Best Practice: The domain logic should be abstracted from the Controller and placed in its own domain-specific class.


Struts requires developers to expandActionAnd OverwriteExecute ()To process the request. GenerallyActionClasses provide very specific work units. Figure 3 demonstrates three specific actions:Saveorderaction,DeleteorderactionAndListordersaction. The front-end controller will callExecute ()Methods, including HTTP request and response objects.ActionformIs a class that can easily transmit back and forth to the view and verify the input related to the form,ActionmappingContains the ing configuration information, as described in XML in Figure 2.



Execute ()Method returnActionforwardStruts uses this object to determine the component that continues processing the request. In general, this component is a JSP page,ActionforwardIt can also point to other actions. The developer must be clear that what struts creates isActionAnd allows multiple threads to call itsExecute (). This makes request processing faster, because the framework does not need to frequently create newActionInstance. However, because a single object can be shared among multiple threads, appropriate thread considerations must be observed, because other threads may destroy instance variables that are maintained in this action.



In rails, it must be extended.Actioncontroller: BaseTo involve the model in request processing. Rails does not setActioncontrollerInstead, it creates a new instance for each request. Although this may have a negative impact on performance, it can make development easier. Developers do not need to pay attention to the thread issues in struts. Therefore, sessions, requests, headers, and parameters can all be usedActioncontroller.ActioncontrollerIt is also a reasonable place to combine all the processing of specific domain logic. StrutsActionClass is fine-grained, it provides very specific work units, while railsActioncontrollerIt is coarse-grained, And it simulates specific work units as some methods.



Listing 1 and Listing 2 demonstrate typical struts actions and typical rails actions respectively.



Table 1 compares the logical flows of the two methods and demonstrates what happens in the specific rows of Listing 1 and Listing 2. ResearchDeleteorderactionOfExecute ()Method andOrdercontrollerOfDeleteMethods, we can see that they are basically the same.



Table 1. Comparison of execute () and delete Methods


step struts rails
framework call Action row 03: execute () row 07: Delete
the ID retrieved from the request row 06-07: retrieve from the request object row 08: retrieve from the instance hash of all parameters
delete order records from the database line 09, 14-24: call theDelete ()method and use hibernate to delete records row 09: delete a record with activerecord
redirect to list remaining orders row 11: use theactionmappingobject to find the next component to be forwarded. The XML ing in Figure 2 shows thatsuccessmaps to/listorders, which is anotheraction, searches for remaining orders and presents them as JSP Row 10: theredirect_tomethod is called by hashing the next called action. In this case, it only calls theListmethod of the same controller


Persistence framework
Persistence frameworkIt is used to move data back and forth between the application layer and the database. The Persistence frameworks of Hibernate and rails can be classified as object/relational ing (ORM) tools, which means they accept the object view of data and map the view to the tables in the relational database. The two frameworks are used to reduce the development time related to relational databases. However, figure 4 demonstrates some fundamental differences between the two in design and configuration.



Figure 4. Comparison of the active record and Hibernate Persistence frameworks






Figure 4. Comparison of the active record and Hibernate Persistence frameworks



Hibernate
Hibernate is based on the data mapper mode. In this mode, a specific er ClassSessionStores and retrieves data permanently in the database. Hibernate can persistently store anyJavaObject, as long as the object complies with the an specification. The XML ing file describes how to map a class to a specific table in the database, and describes the relationship between the class and other classes.



Listing 3 shows an instance of the hibernate ing file.ClassTagOrderObject ingOrdersTable, there are many sub-labels used to describe its properties, Id order name, and the sameModels. Item. Listing 4 showsOrderClass.



Listing 3. Order. HBM. xml


... 01 


Listing 4. Order. Java


01 public class order {02 private set items; 03 private string name; 04 private long ID; 05 06 public long GETID () {return ID ;} 07 08 public void setid (long ID) {This. id = ID;} 09 10 public set getitems () {return items;} 11 12 public void setitems (set items) {This. items = items;} 13 14 Public String getname () {return name;} 15 16 public void setname (string name) {This. name = Name;} 17}


Active record





reflection and metaprogramming
Wikipedia (see references) reflection is briefly defined as "the ability of a program to check and modify its advanced structure while it is running ". Where metaprogramming is also defined as "writing programs that can write and operate other programs (or themselves ), use other programs as their own data programs, or write programs that complete part of the work done by other programs at runtime."

the following code implements reflection:

 01 OBJ = "some_string" 02 if obj. respond_to? ('Length'): 03 puts "OBJ length = # {obj. Length}" 03 end> OBJ length = 5

This code implements metaprogramming:

 01 class someclass02 end03 newmethod = % q {def MSG () puts "a message! "End} 04 someclass. class_eval (newmethod) 05 Aclass = someclass. new06 Aclass. MSG> a message!


The ORM framework of rails is calledActive recordIt is based on the design pattern of the same name. Martin Fowler describes active record as "the object that wraps data rows in database tables or views, encapsulates database access, and adds domain logic to data ". In rails, each domain object will be extended to provide crud operationsActiverecord: Base.



Like hibernate, active record does not need to map files. In fact, developers using active record do not need to encode the attributes of getter, setter, and even classes. Through some beautiful vocabulary analysis, the active record can determine,OrderClass will be mapped to the databaseOrdersTable. Using a combination of Ruby reflection and metaprogramming, the columns of a table can be changed to object attributes. The accessors and runners are also added.



Listing 5 showsOrderThe code after the completion of the class. InOrderA line of code in the class definesItemObject relationship.Has_manyIs a static method call, symbol: ItemsIs its parameter. Activerecord: ItemsFoundItemDomain object, and thenItemObject ing back to databaseItemsTable.



Listing 5. Order. Rb


01 class order <activerecord: base02has_detail: items03 end


Encoded as in listing 5OrderClasses provide some classes and instance methods at runtime. Table 2 providesOrderList of the operations and properties used on:



Table 2. Available attributes and operations on order


Class Method Instance method Attribute
  • Find (* ARGs)
  • find_by_ SQL (SQL)
  • exists? (ID)
  • Create (attributes)
  • Update (ID, attributes)
  • update_all (updates, conditions
  • Delete (ID)
  • delete_all (Conditions)
  • ...
  • add_items
  • build_to_items
  • create_in_items
  • find_all_in_items
  • find_in_items
  • has_items?
  • items
  • items =
  • items_count
  • remove_items
  • id
  • name


Conclusion
Although Ruby on Rails is a very new and exciting framework, it has aroused considerable interest in the web community, however, its core architecture still follows the basic pattern found in J2EE. Developing a web application that separates the two frameworks is a reasonable method. Rails prefers clear code rather than configuration files, while the dynamic nature of Ruby generates a majorityMPs queueCode. Most rails frameworks are created as independent projects, and application development can benefit from a group of similar components. In contrast, a typical J2EE stack tends to be built on the best components that are normally independently developed. It is often configured in XML and combined.



So should we consider using rails for the next web application? Well, why not? It is a well-written component stack that works well with each other and is based on industry-accepted enterprise models. The ruby language supports rapid development and is added to the framework by producing most application pipelines. People familiar with MVC and ORM frameworks in the Java World do not have any difficulty in expressing their own ideas with rails.



Will distribution with J2EE be beneficial to rails? Absolutely not. J2EE is a set standard with many fixed implementations, and, most importantly, it is a proven technology. I suggest you download a copy of rails and study it yourself. Many of the available tutorials are introductory. These tutorials allow you to start using rails immediately. Again, I cannot guarantee that you will be happy by using rails, but I bet you will be satisfied.





Related Article

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.