Ruby on Rails and J2EE: Can they coexist?

Source: Internet
Author: User
Tags ruby on rails
Ruby on Rails and J2EE: Can they coexist?

Comparison of Two Web Application Frameworks

Document options

<Tr valign = "TOP"> <TD width = "8"> </TD> <TD width = "16"> </ TD> <TD class = "small" width = "122"> <p> <SPAN class = "Ast"> the required JavaScript document options are not displayed </span> </P> </TD> </tr>


Send this page as an email


Level: elementary

Aaron rustad, technical architect, anassina, Inc.

August 11, 2005

Ruby on Rails is a relatively new web application framework 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 has caused great controversy between rails and the J2EE community, it 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, less code is required than most frameworks spend on XML processing.

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 a Web server, a framework for processing HTTP requests and responses, and a framework for convenient persistent storage of data to relational databases. 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

Procedure Struts Rails
Framework call Action Row 03: execute() Row 07: delete
Id retrieved from the request Line 06-07:Retrieve from request object Row 08:Retrieve from instance hash of all parameters
Delete order records from database Rows 09, 14-24:Calldelete()Method: Use hibernate to delete records Row 09:Delete a record with activerecord
Redirect to list remaining orders Row 11:UseActionMappingThe object searches for the next component to be forwarded. XML ing in Figure 2 is displayed,successMap/listOrders, This is anotherActionTo find the remaining orders and present them as JSP Row 10:Use the hash of the next called action to callredirect_toMethod; in this case, it only callslistMethod



Back to Top

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 aim 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

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 any Java object, 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 02 <class name="models.Order" table="ORDERS"
03 dynamic-update="true" dynamic-insert="false"
04 discriminator-value="null">
05
06 <id name="id" column="id" type="java.lang.Long"
07 unsaved-value="null">
08 <generator class="identity"/>
09 </id>
10
11 <set name="items" lazy="false" inverse="false"
12 cascade="none" sort="unsorted">
13 <key column="id"/>
14 <one-to-many class="models.Item"/>
15 </set>
16
17 <property name="name" type="java.lang.String"
18 update="true" insert="true"
19 access="property" column="name"/>
20 </class>
21

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

In Wikipedia (see references ),ReflectionIt is defined as "the ability of the program to check and modify its advanced structure during running ". ThereMetaprogrammingIt is defined as "writing programs that can write and operate other programs (or themselves) and use other programs as their own data, 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 will implement metaprogramming:

01 class SomeClass
02 end
03 newMethod = %q{def msg() puts "A message!" end}
04 SomeClass.class_eval(newMethod)
05 aClass = SomeClass.new
06 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::Base
02has_many :items
03 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



Back to Top

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.

References

  • For more information, see the original article on the developerworks global site.

  • Related content:
    • Use Ruby on Rails to quickly develop Web Applications
    • Struts, an open source implementation of MVC
    • No container object relationship ing required

  • See Ruby on Rails Web site.
  • Get the latest information you need to know about Ruby from the ruby-lang.org.
  • We found more information about struts and Jakarta projects.
  • Learn more about hibernate.
  • Get a good introduction to creating a rails application from "rolling with Ruby on Rails" (onlamp.com, January 2005) written by curt Hibbs.
  • Find a brief description of the Model-View-controller and Front Controller modes in Sun's blueprints directory.
  • On Martin Fowler's Web site, learn about the simplified description of the active record and data mapper modes.
  • Master fast-track your web apps with Ruby on Rails, in this way, you can use this ruby-based framework and Its Model-View-controller design pattern to quickly build and customize applications (developerworks, June 2005 ).
  • Starting with programming in the ruby language (developerworks, July 2001), we have studied ruby and its variables, references, arrays, objects, and methods.
  • In struts, an open-source implementation of MVC, study how struts helps control changes in web projects and improve your expertise (developerworks, February 2001 ).
  • In object-Relation Mapping without the container, learn how to use Hibernate and spring to build a transactional persistent storage layer for enterprise applications (developerworks, April 2004 ).
  • See Wikipedia's reflection and metaprogramming definitions.
  • See the developerworks Web architecture area for articles on various web-based solutions.
  • Join the developerworks community by joining developerworks blogs.

About the author

Aaron rustad has been working on Java since 1998 and has been an architect and developer for J2EE applications in some vertical markets, including oil and gas, agriculture and education. You can contact Aaron via arustad@gmail.com.

 

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.