JSF与Struts的异同

JSFStruts的异同

板桥里人 http://www.jdon.com 2005/09/05

  StrutsJSF/Tapestry都属于表现层框架,这两种分属不同性质的框架,后者是一种事件驱动型的组件模型,而Struts只是单纯的MVC模式框架,老外总是急吼吼说事件驱动型就比MVC模式框架好,何以见得,我们下面进行详细分析比较一下到底是怎么回事?

  首先事件是指从客户端页面(浏览器)由用户操作触发的事件,Struts使用Action来接受浏览器表单提交的事件,这里使用了Command模式,每个继承Action的子类都必须实现一个方法execute

  在struts中,实际是一个表单Form对应一个Action(DispatchAction),换一句话说:在Struts中实际是一个表单只能对应一个事件,struts这种事件方式称为application eventapplication eventcomponent event相比是一种粗粒度的事件。

  struts重要的表单对象ActionForm是一种对象,它代表了一种应用,这个对象中至少包含几个字段,这些字段是Jsp页面表单中的input字段,因为一个表单对应一个事件,所以,当我们需要将事件粒度细化到表单中这些字段时,也就是说,一个字段对应一个事件时,单纯使用Struts就不太可能,当然通过结合JavaScript也是可以转弯实现的。

  而这种情况使用JSF就可以方便实现,

<h:inputText id="userId" value="#{login.userId}">
  <f:valueChangeListener type="logindemo.UserLoginChanged" />
</h:inputText>

  #{login.userId}表示从名为loginJavaBeangetUserId获得的结果,这个功能使用struts也可以实现,name="login" property="userId"

  关键是第二行,这里表示如果userId的值改变并且确定提交后,将触发调用类UserLoginChangedprocessValueChanged(...)方法。

  JSF可以为组件提供两种事件:Value Changed Action. 前者我们已经在上节见识过用处,后者就相当于struts中表单提交Action机制,它的JSF写法如下:

<h:commandButton id="login" commandName="login">
  <f:actionListener type=”logindemo.LoginActionListener” />
</h:commandButton>

  从代码可以看出,这两种事件是通过Listerner这样观察者模式贴在具体组件字段上的,而Struts此类事件是原始的一种表单提交Submit触发机制。如果说前者比较语言化(编程语言习惯做法类似Swing编程);后者是属于WEB化,因为它是来自Html表单,如果你起步是从Perl/PHP开始,反而容易接受Struts这种风格。

基本配置

  StrutsJSF都是一种框架,JSF必须需要两种包JSF核心包、JSTL包(标签库),此外,JSF还将使用到Apache项目的一些commons包,这些Apache包只要部署在你的服务器中既可。

  JSF包下载地址:http://java.sun.com/j2ee/javaserverfaces/download.html选择其中Reference Implementation

  JSTL包下载在http://jakarta.apache.org/site/downloads/downloads_taglibs-standard.cgi

  所以,从JSF的驱动包组成看,其开源基因也占据很大的比重,JSF是一个SUN伙伴们工业标准和开源之间的一个混血儿。

  上述两个地址下载的jar合并在一起就是JSF所需要的全部驱动包了。与Struts的驱动包一样,这些驱动包必须位于Web项目的WEB-INF/lib,和Struts一样的是也必须在web.xml中有如下配置:

<web-app>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
</web-app>

  这里和Strutsweb.xml配置何其相似,简直一模一样。

  正如Strutsstruts-config.xml一样,JSF也有类似的faces-config.xml配置文件:


<faces-config>
  <navigation-rule>
    <from-view-id>/index.jsp</from-view-id>
    <navigation-case>
      <from-outcome>login</from-outcome>
      <to-view-id>/welcome.jsp</to-view-id>
    </navigation-case>
  </navigation-rule>

  <managed-bean>
    <managed-bean-name>user</managed-bean-name>
    <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>
</faces-config>

 

  在Struts-config.xml中有ActionForm Action以及Jsp之间的流程关系,在faces-config.xml中,也有这样的流程,我们具体解释一下Navigation

  在index.jsp中有一个事件:

<h:commandButton label="Login" action="login" />

  action的值必须匹配form-outcome值,上述Navigation配置表示:如果在index.jsp中有一个login事件,那么事件触发后下一个页面将是welcome.jsp

  JSF有一个独立的事件发生和页面导航的流程安排,这个思路比struts要非常清晰。

  managed-bean类似StrutsActionForm,正如可以在struts-config.xml中定义ActionFormscope一样,这里也定义了managed-beanscopesession

  但是如果你只以为JSFmanaged-bean就这点功能就错了,JSF融入了新的Ioc模式/依赖性注射等技术。

Ioc模式

  对于Userbean这样一个managed-bean,其代码如下:

public class UserBean {
  private String name;
  private String password;

  // PROPERTY: name
  public String getName() { return name; }
  public void setName(String newValue) { name = newValue; }

  // PROPERTY: password
  public String getPassword() { return password; }
  public void setPassword(String newValue) { password = newValue; }
}

<managed-bean>
  <managed-bean-name>user</managed-bean-name>
  <managed-bean-class>com.corejsf.UserBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>

  <managed-property>
    <property-name>name</property-name>
    <value>me</value>
  </managed-property>

  <managed-property>
    <property-name>password</property-name>
    <value>secret</value>
  </managed-property>
</managed-bean>

  faces-config.xml这段配置其实是将"me"赋值给name,将secret赋值给password,这是采取Ioc模式中的Setter注射方式

Backing Beans

  对于一个web form,我们可以使用一个bean包含其涉及的所有组件,这个bean就称为Backing Bean Backing Bean的优点是:一个单个类可以封装相关一系列功能的数据和逻辑。

  说白了,就是一个Javabean里包含其他Javabean,互相调用,属于Facade模式或Adapter模式。


  对于一个Backing Beans来说,其中包含了几个managed-beanmanaged-bean一定是有scope的,那么这其中的几个managed-beans如何配置它们的scope呢?

<managed-bean>
  ...
  <managed-property>
    <property-name>visit</property-name>
    <value>#{sessionScope.visit}</value>
  </managed-property>

  这里配置了一个Backing Beans中有一个setVisit方法,将这个visit赋值为session中的visit,这样以后在程序中我们只管访问visit对象,从中获取我们希望的数据(如用户登陆注册信息),而visit是保存在session还是applicationrequest只需要配置既可。

UI界面

  JSFStruts一样,除了JavaBeans类之外,还有页面表现元素,都是是使用标签完成的,Struts也提供了struts-faces.tld标签库向JSF过渡。

  使用Struts标签库编程复杂页面时,一个最大问题是会大量使用logic标签,这个logic如同if语句,一旦写起来,搞的JSP页面象俄罗斯方块一样,但是使用JSF标签就简洁优美:

<jia:navigatorItem name="inbox" label="InBox"
  icon="/images/inbox.gif"
  action="inbox"
  disabled="#{!authenticationBean.inboxAuthorized}"/>

  如果authenticationBeaninboxAuthorized返回是假,那么这一行标签就不用显示,多干净利索!

  先写到这里,我会继续对JSF深入比较下去,如果研究过Jdon框架的人,可能会发现,Jdon框架的jdonframework.xmlservice配置和managed-bean一样都使用了依赖注射,看来对Javabean的依赖注射已经迅速地成为一种新技术象征,如果你还不了解Ioc模式,赶紧补课。

 

 

 

 

 

 

 

 

 

 

 

 

 

JavaServer Faces (JSF) vs Struts

A brief comparison

By: Roland Barcia

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.

posted on 2005-10-28 15:47 guyue 阅读(288) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: