Welcome!

Websphere Authors: Carmen Gonzalez, Yeshim Deniz, Elizabeth White, Sanjeev Sharma, Liz McMillan

Related Topics: Java

Java: Article

JavaServer Faces (JSF) vs Struts

A brief comparison

My JSF article series and Meet the Experts appearance on IBM developerWorks received a lot of feedback.

I would have to say, the most common question or feedback came along the lines of comparing Struts to JSF. I thought it would be a good idea to compare JSF to Struts by evaluating various features that an application architect would look for in a Web application framework. This article will compare specific features. Those on which I will focus include:

  • Maturity
  • Controller Flexibility/Event Handling
  • Navigation
  • Page development
  • Integration
  • Extensibility

Certainly, there are other places in which you might want to do a comparison, such as performance, but I'll focus on the set I just mentioned. I'll also spend more time on the Controller and Navigation sections because they are the heart of the frameworks. Performance of JSF is specific to the vendor implementation, and I always encourage people to perform their own performance tests against their own set of requirements because there are too many factors that can affect performance. A performance evaluation would be unfair. Other areas such as page layout, validation, and exception handling were also left out in the interest of saving space.

Maturity

Struts has been around for a few years and has the edge on maturity. I know of several successful production systems that were built using the Struts framework. One example is the WebSphere Application Server Web-based administrative console. JavaServer Faces(JSF), however, has been in draft for 2 years. Several companies, including IBM as well as the creator of Struts, Craig McClanahan, have contributed to the creation of JSF during that time. Nonetheless, it will take some time to see a few systems deployed.

Struts definitely has the edge in this category. With JSF, however, you can rely on different levels of support depending on which implementation you choose. For example, the JSF framework inside WebSphere Studio comes with IBM support.

Controller Flexibility/Event Handling

One of the major goals of Struts was to implement a framework that utilized Sun's Model 2 framework and reduced the common and often repetitive tasks in Servlet and JSP development. The heart of Struts is the Controller. Struts uses the Front Controller Pattern and Command Pattern. A single servlet takes a request, translates HTTP parameters into a Java ActionForm, and passes the ActionForm into a Struts Action class, which is a command. The URI denotes which Action class to go to. The Struts framework has one single event handler for the HTTP request. Once the request is met, the Action returns the result back to the front controller, which then uses it to choose where to navigate next. The interaction is demonstrated in Figure 1.

JSF uses the Page Controller Pattern. Although there is a single servlet every faces request goes through, the job of the servlet is to receive a faces page with components. It will then fire off events for each component and render the components using a render toolkit. The components can also be bound to data from the model. The faces life-cycle is illustrated in Figure 2.

JSF is the winner in this area, because it adds many benefits of a front controller, but at the same time gives you the flexibility of the Page Controller. JSF can have several event handlers on a page while Struts is geared to one event per request. In addition, with Struts, your ActionForms have to extend Struts classes, creating another layer of tedious coding or bad design by forcing your model to be ActionForms. JSF, on the other hand, gives developers the ability to hook into the model without breaking layering. In other words, the model is still unaware of JSF.

Navigation

Navigation is a key feature of both Struts and JSF. Both frameworks have a declarative navigation model and define navigation using rules inside their XML configuration file. There are 2 types of navigation: static navigation - when one page flows directly to the next; and dynamic navigation - when some action or logic determines which page to go to.

Both JSF and Struts currently support both types of navigation.

Struts
Struts uses the notion of forwards to define navigation. Based on some string, the Struts framework decides which JSP to forward to and render. You can define a forward by creating an Action as shown in the snippet below.

<action path="/myForward" forward="/target.jsp"> </action>

Struts supports dynamic forwarding by defining a forward specifically on an Action definition. Struts allows an Action to have multiple forwards.

 


<action-mappings>
		<action name="myForm" path="/myACtion" scope="request"
		 type="strutsnav.actions.MyAction">
			<forward name="success" path="./target.jsp">
			</forward>
			<forward name="error" path="./error.jsp">
			</forward>

		</action>
	</action-mappings>

Developers can then programmatically choose which forward to return.

 


public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {

		ActionErrors errors = new ActionErrors();
		ActionForward forward = new ActionForward(); // return value
		MyForm myForm = (MyForm) form;

		try {

			// do something here

		} catch (Exception e) {

			// Report the error using the appropriate name and ID.
			errors.add("name", new ActionError("id"));
			forward = mapping.findForward("success");
			return (forward);
		}

		forward = mapping.findForward("success");
		return (forward);

	}

JSF Static Navigation
JSF supports navigation by defining navigation rules in the faces configuration file. The example below shows a navigation rule defining how one page goes to the next.

 


<navigation-rule>
		<from-view-id>/FromPage.jsp</from-view-id>
		<navigation-case>
			<from-outcome>success</from-outcome>
			<to-view-id>/ToPage.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

However, unlike Struts, JSF navigation is applied on the page level and can be action-independent. The action is hard coded into the component allowing for finer grain control on the page. You can have various components on the page define different actions sharing the same navigation rule.

<hx:commandExButton type="submit" value="Submit"
styleClass="commandExButton" id="button1" action="success" />

JSF also supports dynamic navigation by allowing components go to an action handler.

<hx:commandExButton type="submit" value="Submit"
styleClass="commandExButton" id="button1" action="#
{pc_FromPage.doButton1Action}" />

Developers can then code action handlers on any class to make the dynamic navigation decision.

 


public String doButton1Action() {
		return "success";
	}

Even though navigation rules don't need to specify the action in order to support dynamic navigation, JSF allows you to define the action on the navigation rule if you so choose. This allows you to force a specific navigation rule to go through an action.

 


<navigation-rule>
		<from-view-id>/FromPage.jsp</from-view-id>
		<navigation-case>
			<from-action>#{pc_FromPage.doButton1Action}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/ToPage.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

Both Struts and JSF are pretty flexible from a navigation stand point, but JSF allows for a more flexible approach and a better design because the navigation rule is decoupled from the Action. Struts forces you to hook into an action, either by a dummy URI or an action class. In addition, it is easier in JSF to have one page with various navigation rules without having to code a lot of if-else logic.

Page Development

JSF was built with a component model in mind to allow tool developers to support RAD development. Struts had no such vision. Although the Struts framework provides custom libraries to hook into Action Forms and offers some helper utilities, it is geared toward a JSP- and HTTP-centric approach. SF provides the ability to build components from a variety of view technologies and does it in such a way to be toolable. JSF, therefore, is the winner in this area.

Integration

Struts was designed to be model neutral, so there is no special hooks into a model layer. There are a view reflection-based copy utilities, but that's it. Usually, page data must be moved from an Action Form into another Model input format and requires manual coding. The ActionForm class, provides an extra layer of tedious coding and state transition.

JSF, on the other hand, hides the details of any data inside the component tree. Rich components such as data grids can be bound to any Java class. This allows powerful RAD development, such as the combination of JSF and SDO. I will discuss this further in future articles.

Extensibility

Both Struts and JSF provides opportunities to extend the framework to meet expanding requirements. The main hook for Struts is a RequestProcessor class that has various callback methods throughout the life-cycle of a request. A developer can extend this class to replace or enhance the framework.

JSF provides equivalent functionality by allowing you to extend special life-cycle interfaces. In addition, JSF totally decouples the render phase from the controller allowing developers to provide their own render toolkits for building custom components. This is one of the powerful features in JSF that Struts does not provide. JSF clearly has the advantage in this area.

Conclusion

In general, JSF is a much more flexible framework, but this is no accident. Struts is a sturdy framework and works well. JSF was actually able to learn a great deal from Struts projects. I see JSF becoming a dominant framework because of its flexible controller and navigation. Furthermore, JSF is built with integration and extensibility in mind. If you are starting a new project today, you'd have to consider many factors. If you have an aggressive schedule with not much time to deal with evaluating different vendors or dealing with support for new JSF implementations, Struts may be the way to go. But from a strategic direction and programming model, JSF should be the target of new applications. I encourage developers to take time to learn JSF and begin using them for new projects. In addition, I would consider choosing JSF vendors based on component set and RAD tools. JSF isn't easier than Struts when developing by hand, but using a RAD JSF tool like WebSphere Studio can greatly increase your productivity.

References

  • Developing JSF Applications Using WebSphere Studio: www-106.ibm.com/developerworks/ websphere/techjournal/0401_barcia/barcia.html
  • Developing JavaServer Faces Portlets Using WebSphere Studio: www-106.ibm.com/developerworks/ websphere/techjournal/0406_barcia/0406_barcia.html
  • Meet the Experts: Roland Barcia on JSF and JMS: www-106.ibm.com/developerworks/websphere/ library/techarticles/0407_barcia/0407_barcia.html
  • JSF Central: www.jsfcentral.com
  • IBM WebSphere -Deployment and Advanced Configuration: Click Here !
  • More Stories By Roland Barcia

    Roland Barcia is a consulting IT specialist for IBM Software Services for WebSphere in the New York/New Jersey Metro area. He is the author of one of the most popular article series on the developerWorks WebSphere site, www-106.ibm.com/developerworks/websphere/techjournal/0401_barcia/barcia.html, and is also a coauthor of IBM WebSphere: Deployment and Advanced Configuration. You can find more information about him at http://web.njit.edu/~rb54

    Comments (10) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    lguerin 12/08/10 09:03:00 AM EST

    And what about the full-stack frameworks ?

    For example Telosys http://www.telosys.org an emerging framework with Eclipse plugin for scaffolding.

    It's more simple and easy to use.

    alen_smith 12/02/08 09:51:11 PM EST

    Hello.
    I `m H.dorin . I `m a java developer.
    Today I want to speak about a new J2EE framework to name SHINE , that I read several document and comment about that.
    In many of these documents complimented about shine whereas even a big project also do not implemented with shine framework.
    Nonetheless When I see these compliment about shine framework, and I see PAUCITY documents about shine`s shortcomings, I be enthusiastic fore learning more about shine framework.
    Therefore I download shine frame work from http://sourceforge.net/projects/shine-app/ and deploy several sample with that.(those samples that write with shine support team)
    I must avowal shine frame worke have a powerful architecture and have simple usage,
    But:
    To my idea it`s soon for praise shine framework and shine`s ability because of shine not tested by high developer and not implemented a big project with it.

    of course some of shine`s abilitys such as " it is SERVICE ORIENTED , working with AJAX in shine is easy , support MVC and shine is easy to use " is demonstrator a powerful framework,

    but:
    some ability of shine such as JWMS ARCHITECTUR that saying it `s shine framework`s special Architecture , is a new Architecture and nobody don`t understand what is it(like me). And in my search in internet I understand is not any document about that. I don`t know why some developers compliment than JWMS .
    to my Idea it `s soon for discussion about shine`s abilitys with this confidence and I can`t implement my project with it because it `s new and unpromising , until developers impelement several project with it and accept it such as a powerful J2ee framework.

    however I belive shine will be a good frame work in future. but for now, it `s not a confident j2ee frame work.

    This text is only my Idea and if some one have any proof unlike my idea , his/her can discuss it.

    Jan Naude 01/16/08 10:55:10 AM EST

    Relating to Doug Smith's question:

    Doug, I think you misunderstand MVC. The components are:

    Model (data retrieved/manipulated by business rules)
    View (responsible for rendering/displaying relevant information to user)
    Controller - business logic that operates on/manipulates model to produce data to be displayed by view.

    The idea with MVC is not to mix business logic (i.e. Servlets/Struts actions) and presentation logic (jsp/html) in the same artifacts (components), because then you end up not being able to replace/change one without having to replace/change the other.
    JSF focuses more on easily developing the View part, while Struts concentrates more on Model and Controller and their integration.

    Jose Arco 11/14/07 10:49:52 AM EST

    Hi,
    Really interesting article.
    I have a related question. We have a web acces application based completly on Struts. Now we want to add a new funcionality based on JSF, the question is if we could have integration problems between both tools.
    Thanks in advanced

    bill 10/26/07 10:07:33 AM EDT

    it would be nice to redo this comparison TODAY in 2007 and see what comes out. Struts2 has really added a ton to their side and JSF components have matured.

    I would like to see a modern comparison- as there does not seem to be one.

    wildcat 04/05/05 12:09:03 AM EDT

    Hi,
    Yes JSF is the way to go. The thing which I like the most about JSF is the finer control given by the component based architechture which is the key for RAD tools..like .NET.
    Java is up there facing a string competition form .NET but hey JAVA will WIN.

    Doug Smith 10/19/04 05:57:05 PM EDT

    Friends, this is going to sound like a really dumb question, but I am asking in all sincerity.

    While I understand the arguments to separate view (screen) from model (database & rules) & control (keyboard), I'm not sure I understand why I need Struts or JSF to do this. I can put code a View as a JSP, interact with the Model using Javabeans, and exercise Control using HTML or JSP directives.

    What exactly are the benefits using either Struts or JSF? The cost is obvious - another set of things to learn and configure.

    (Asked by a solo practitioner who doesn't work with graphic designers).

    David Thirakul 10/18/04 04:31:52 PM EDT

    Very interesting article, thank you. We are currently working extensively with Struts for the presentation layer and are watching the progress of JSF with much interest because it seems to be the way to go in the long term. There is no doubt that JSF will take over as McClanahan stated himself when he was talking about migrating to JSF.
    (see http://www.theserverside.com/news/thread.tss?thread_id=29068). There's no new development on Struts as opposed to JSF which by the way is the answer to MS webforms. So to answer Tom's comment, yes there is overlaping and if you start a new project from scratch and want to compare struts and jsf, roland's article is very insightful. What I would like to point out also is that JSF seem to lack the ease of use and functionnality of webforms, that's why all the new development goes into JSF, there's a lot of catching up to do...

    Roland Barcia 10/01/04 08:31:42 PM EDT

    Thanks for the feedback. Craig has a vested interest in both frameworks. There are features in Struts that compliment JSF like Tiles and the Validation framework. But just because they have some areas where they can work together does not mean I cannot compare them both. In this article, I focus on the Core of the frameworks and how they differ. I see very little benefit with the current Struts implementation to mix the Struts controller with the JSF components.

    Tom Roche 09/30/04 03:51:40 PM EDT

    To speak of "JSF vs Struts" displays a lack of understanding of the
    different specializations of the two frameworks. JSF specializes in
    view, Struts in model and control. The two can be used together via
    the Struts-Faces Integration Library. As Craig McClanahan's inaugural
    blog post

    http://blogs.sun.com/roller/page/craigmcc/20040927#struts_or_jsf_struts_and

    points out:

    > For new development, here's the best strategy for determining what
    > to do:

    > * Evaluate the two technologies individually, to see if they satisfy
    > your requirements.

    > * If one or the other technology is sufficient, go ahead and use it
    > (it's easier to learn and use one technology rather than two where
    > possible); keeping in mind, however, the caveats about Struts HTML
    > tags mentioned above.

    > * If your requirements include unique features supported only by
    > Struts (such as Tiles or client side validation support), feel
    > free to use the two frameworks together.

    > The Future

    > It should be clear by now that there is overlap between Struts and
    > JSF, particularly in the view tier. Over time, JSF will continue to
    > evolve in the view tier area, and I'm going to be encouraging the
    > Struts community to focus on value adds in the controller and model
    > tiers.

    @ThingsExpo Stories
    Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
    The Internet of Things is tied together with a thin strand that is known as time. Coincidentally, at the core of nearly all data analytics is a timestamp. When working with time series data there are a few core principles that everyone should consider, especially across datasets where time is the common boundary. In his session at Internet of @ThingsExpo, Jim Scott, Director of Enterprise Strategy & Architecture at MapR Technologies, discussed single-value, geo-spatial, and log time series data. By focusing on enterprise applications and the data center, he will use OpenTSDB as an example t...
    P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at @ThingsExpo, Robin Raymond, Chief Architect at Hookflash, will walk through the shifting landscape of traditional telephone and voice services ...
    The Domain Name Service (DNS) is one of the most important components in networking infrastructure, enabling users and services to access applications by translating URLs (names) into IP addresses (numbers). Because every icon and URL and all embedded content on a website requires a DNS lookup loading complex sites necessitates hundreds of DNS queries. In addition, as more internet-enabled ‘Things' get connected, people will rely on DNS to name and find their fridges, toasters and toilets. According to a recent IDG Research Services Survey this rate of traffic will only grow. What's driving t...
    Enthusiasm for the Internet of Things has reached an all-time high. In 2013 alone, venture capitalists spent more than $1 billion dollars investing in the IoT space. With "smart" appliances and devices, IoT covers wearable smart devices, cloud services to hardware companies. Nest, a Google company, detects temperatures inside homes and automatically adjusts it by tracking its user's habit. These technologies are quickly developing and with it come challenges such as bridging infrastructure gaps, abiding by privacy concerns and making the concept a reality. These challenges can't be addressed w...
    Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, described how to revolutioniz...
    Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
    The definition of IoT is not new, in fact it’s been around for over a decade. What has changed is the public's awareness that the technology we use on a daily basis has caught up on the vision of an always on, always connected world. If you look into the details of what comprises the IoT, you’ll see that it includes everything from cloud computing, Big Data analytics, “Things,” Web communication, applications, network, storage, etc. It is essentially including everything connected online from hardware to software, or as we like to say, it’s an Internet of many different things. The difference ...
    Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world.
    SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
    "There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
    The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...

    ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

    An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
    Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
    The security devil is always in the details of the attack: the ones you've endured, the ones you prepare yourself to fend off, and the ones that, you fear, will catch you completely unaware and defenseless. The Internet of Things (IoT) is nothing if not an endless proliferation of details. It's the vision of a world in which continuous Internet connectivity and addressability is embedded into a growing range of human artifacts, into the natural world, and even into our smartphones, appliances, and physical persons. In the IoT vision, every new "thing" - sensor, actuator, data source, data con...
    "BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
    Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
    C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
    The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.