中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > Java > 设计模式
Take Command of Your Software (3)
作者:未知 时间:2005-07-24 21:23 出处:JR 责编:chinaitpower
              摘要:Take Command of Your Software (3)

Example 2. WEB-INF/web.xml

 
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <!DOCTYPE web-app
  3.   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  4.   "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
  5. <web-app>
  6.   <!-- Action Servlet Configuration -->
  7.   <servlet>
  8.     <servlet-name>
  9.        action
  10.     </servlet-name>
  11.     <servlet-class>
  12.       org.apache.struts.action.ActionServlet
  13.     </servlet-class>
  14.     ...
  15.     <init-param>
  16.       <param-name>config</param-name>
  17.       <param-value>/WEB-INFaction.xml</param-value>
  18.     </init-param>
  19.     ...
  20.   </servlet>
  21.   <!-- Action Servlet Mapping -->
  22.   <servlet-mapping>
  23.     <servlet-name>action</servlet-name>
  24.     <url-pattern>*.do</url-pattern>
  25.   </servlet-mapping>
  26.   ...
  27. </web-app>


The preceding deployment descriptor does three things: 
  1. Maps the name action to the Struts action servlet (org.apache.struts.action.ActionServlet)
  2.  
  3. Creates an initialization parameter for the action servlet that specifies a Struts configuration file (/WEB-INF/action.xml) 

  4. Maps all URLs that end in .do to the action servlet

Example 3 lists test.jsp, the JSP shown in Figure 6's top picture: 

Example 3. test.jsp 


  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <html>
  3.    <head>
  4.      <title>Struts Actions</title>
  5.    </head>
  6.    <body>
  7.      <a href='simple.do'>
  8.        Click Here to Perform a Simple Action
  9.      </a>
  10.    </body>
  11. </html>


The preceding JSP creates an HTML anchor element that references the /simple.do URL. If you click on that link, the Struts action servlet is invoked because the mapping in the deployment descriptor maps all URLs that end in .do to the action servlet (see Example 2). So what does the action servlet do when it receives the /simple.do URL? The answer resides in the Struts configuration file, which is specified in the deployment descriptor (see Example 2) and listed in Example 4: 

Example 4. WEB-INF/action.xml 


  1. <?xml version="1.0" encoding="ISO-8859-1" ?>
  2. <!DOCTYPE struts-config PUBLIC
  3.   "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
  4.   "http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
  5. <struts-config>
  6.    <action-mappings>
  7.       <action path="/simple"
  8.               type="actions.SimpleAction">
  9.          <forward name="fwd-page" path="/forwardPage.jsp"/>
  10.       </action>
  11.    </action-mappings>
  12. </struts-config>


The preceding configuration file maps the /simple URL to the actions.SimpleAction class. When the action servlet receives the /simple.do URL, it strips off the .do suffix and maps the URL to the actions.SimpleAction class. If an instance of that class does not exist, the action servlet creates one and invokes its execute() method. Example 5 lists the actions.SimpleAction class: 

Example 5. WEB-INF/classes/actions/SimpleAction.java 


  1. package actions;
  2. import javax.servlet.ServletContext;
  3. import javax.servlet.http.*;
  4. import org.apache.struts.action.*;
  5. import beans.CounterBean;
  6. public class SimpleAction extends Action {
  7.      public ActionForward execute(ActionMapping mapping, 
  8.                                 ActionForm form,
  9.                                 HttpServletRequest request, 
  10.                                 HttpServletResponse response)
  11.                   throws java.io.IOException
  12.                          javax.servlet.ServletException {
  13.       ActionServlet      servlet = getServlet();
  14.       ServletContext application = servlet.getServletContext();
  15.       CounterBean    counterBean = (CounterBean)application.
  16.                                      getAttribute("counterBean");
  17.       if(counterBean == null) {
  18.          counterBean = new CounterBean();
  19.          application.setAttribute("counterBean", counterBean);
  20.       }
  21.       counterBean.updateCount(request, ".simpleActionCount");
  22.       return mapping.findForward("fwd-page");
  23.    } 
  24. }


The preceding action checks to see if a counter bean exists in the application scope; if not, it creates one and stores it there. Subsequently, the action invokes the counter bean's updateCount() method, which updates a counter stored in a file named .simpleActionCount. Then the action returns an ActionForward instance that points to a JSP mapped to the string fwd-page. That mapping, also defined in the Struts configuration file (see Example 4), resolves the string fwd-page to the forwardPage.jsp JSP. The action servlet subsequently forwards control to that JSP, listed in Example 6: 

Example 6. forwardPage.jsp

 
  1. <%@ taglib uri='/WEB-INFtldsstruts-bean.tld' prefix='struts'%>
  2. <%@ taglib uri='http://java.sun.com/jstl/core' prefix='c'%>
  3. <%@ page import='beans.CounterBean' %>
  4. This simple action has been accessed 
  5. <c:out value='${counterBean.count}'/> 
  6. <c:choose>
  7.    <c:when test='${counterBean.count == 1}'>
  8.       time.
  9.    </c:when>
  10.    <c:otherwise>
  11.       times.
  12.    </c:otherwise>
  13. </c:choose>
  14. <p><c:import url='test.jsp'/>


The preceding JSP uses the JSTL <c:out>, <c:choose>, <c:when>, and <c:otherwise> actions to display information about how many times the counter bean, and therefore the simple action, has been accessed. JSTL defines an expression language that will be incorporated into the upcoming JSP 2.0. The preceding JSP, for example, uses that expression language to access the counter bean in application scope. (You can download JSTL from Resources.) 

Finally, Example 7 lists the counter bean class—beans.CounterBean: 

Example 7. WEB-INF/classes/beans/CounterBean.java 


  1. package beans;
  2. import java.io.*;
  3. import javax.servlet.http.*;
  4. public class CounterBean {
  5.    private int count = 0;
  6.    private File file = null;
  7.    public synchronized void updateCount(HttpServletRequest request,
  8.                                         String filename) 
  9.                                        throws java.io.IOException {
  10.       checkFile(filename);
  11.       readCount();
  12.       count++;
  13.       saveCount();
  14.    }
  15.    public int getCount() {
  16.       return count;
  17.    }
  18.    private void checkFile(String filename) throws IOException {
  19.       if(file == null) {
  20.          file  = new File(filename);
  21.          count = 0;
  22.       }
  23.       if(!file.exists()) {
  24.          file.createNewFile();
  25.          saveCount();
  26.       }
  27.    }
  28.    private void saveCount() throws java.io.IOException {
  29.       FileWriter writer = new FileWriter(file);
  30.       writer.write(count);
  31.       writer.close();
  32.    }
  33.    private void readCount() throws java.io.IOException {
  34.       FileReader reader = new FileReader(file);
  35.       count = reader.read();
  36.       reader.close();
  37.    }
  38. }


The CounterBean class updates the count associated with a particular action. That class serves as a receiver, as I discussed at this article's beginning, by implementing application-specific behavior. 

Your wish is my command

 
Unless you develop application frameworks, you may never need to implement the Command pattern; nevertheless, you should understand how it works so you can effectively use application frameworks such as Swing and Struts. Now that you've seen how to use the Command pattern in Swing and Struts, you'll be able to better use those and other OO frameworks you encounter in the future. 

Homework

 
For your homework assignment, download Struts, then add your own custom action to the example discussed above. That custom action can implement whatever application-specific behavior you desire. 

Homework from last time

 
In your homework assignment from "Strategy for Success" (JavaWorld, April 2002), I asked you to discuss how Swing uses the Strategy pattern in its list class to render list cells. 

As "Strategy for Success" outlined, the Swing JComponent class uses the Strategy pattern to paint borders around components. The JComponent class also uses the Strategy pattern to paint Swing components themselves by delegating that behavior to individual Swing components; for example, the JComponent.paint() method invokes the paintComponent() method, which JComponent subclasses override to paint the component. 

Some Swing components, those with more complicated rendering needs, do not paint themselves; instead, they use the Strategy pattern to delegate that behavior to another object. For example, Swing lists delegate the painting of their list cells to an object that implements the ListCellRenderer interface. That interface defines a single method—getListCellRendererComponent()—that returns a component that paints the list's cells. That Strategy pattern usage lets developers modify how lists paint their cells by implementing a list cell renderer and attaching it to a specific list.
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有