春風博客

          春天里,百花香...

          導航

          <2008年4月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          統計

          公告

          MAIL: junglesong@gmail.com
          MSN: junglesong_5@hotmail.com

          Locations of visitors to this page

          常用鏈接

          留言簿(11)

          隨筆分類(224)

          隨筆檔案(126)

          個人軟件下載

          我的其它博客

          我的鄰居們

          最新隨筆

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          Struts的ActionServlet模擬實現

          Struts中,ActionServlet作為總控Servlet接受請求并轉發到各Action,它的原理并不復雜,本文即展示了ActionServlet模擬實現過程。

          首先,在Web.xml中配置,讓所有url帶.go(struts用的do我用go,特意區分一下)的請求都讓DispatchServlet處理,DispatchServlet就是ActionServlet模擬實現類.

          <?xml version="1.0" encoding="UTF-8"?>
          <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
              xmlns:xsi
          ="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation
          ="http://java.sun.com/xml/ns/j2ee 
              http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
          >

              
          <!-- welcome.jsp -->
              
          <welcome-file-list>
                  
          <welcome-file>/web/page/first.jsp</welcome-file>
              
          </welcome-file-list>

              
          <!-- DispatchServlet -->
              
          <servlet>
                  
          <servlet-name>DispatchServlet</servlet-name>
                  
          <servlet-class>
                      com.sitinspring.action.DispatchServlet
                  
          </servlet-class>
                  
          <init-param>
                      
          <description>Configuration File</description>
                      
          <param-name>configFile</param-name>
                      
          <param-value>web-inf\mockStruts-config.xml</param-value>
                  
          </init-param>
              
          </servlet>

              
          <servlet-mapping>
                  
          <servlet-name>DispatchServlet</servlet-name>
                  
          <url-pattern>*.go</url-pattern>
              
          </servlet-mapping>
          </web-app>

          上面指定了DispatchServlet的初始化參數,DispatchServlet將用它找到配置文件mockStruts-config.xml,這個文件模擬對應著Struts-config.xml.

          DispatchServlet的代碼如下:
          package com.sitinspring.action;

          import javax.servlet.ServletConfig;
          import javax.servlet.ServletContext;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          import com.sitinspring.util.ServletFinder;
          import com.sitinspring.util.StringUtil;

          /**
           * 用于分發命令到其它Servlet的總控Servlet
           * 
          @author sitinspring
           *
           * @date 2008-2-12
           
          */
          public class DispatchServlet extends HttpServlet {
              
          private static final long serialVersionUID = 56890894234786L;

              
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  request.setCharacterEncoding(
          "UTF-8");

                  
          // 通過ServletContext取得工程的絕對物理路徑
                  ServletContext sct = getServletContext();
                  String realPath 
          = sct.getRealPath("/");
                  
                  
          // 通過ServletConfig實例取得初始化參數configFile
                  ServletConfig config=this.getServletConfig();        
                  String mockStrutsCfgFile
          =config.getInitParameter("configFile");
                  
                  
          // 組合配置文件全物理路徑
                  mockStrutsCfgFile=realPath+mockStrutsCfgFile;
                  
                  
          // 取得請求的URI
                  String reqUri=request.getRequestURI();
                  
                  
          // 取得模式匹配字符串,即go,do等
                  String patternStr;
                  
          if(reqUri.contains("?")){
                      patternStr
          =StringUtil.getMatchedString("([.])(.*)?",reqUri);
                  }
                  
          else{
                      patternStr
          =StringUtil.getMatchedString("([.])(.*)$",reqUri);
                  }

                  
          // 取得下一個處理請求的Servlet名
                  String servletName=StringUtil.getMatchedString("/(.*)/(.*)[.]"+patternStr,reqUri);
                  
                  
          // 以Servlet名為基礎從設定文件中取得響應的Servlet類名
                  ServletFinder finder=new ServletFinder(mockStrutsCfgFile,servletName);        
                  String servletClass
          =finder.getServletClass();
                  
                  
          try {
                      
          // 通過反射調用真正的Servlet類進行處理
                      Class cls=Class.forName(servletClass);
                      HttpServlet servlet
          =(HttpServlet)cls.newInstance();
                      servlet.service(request, response);
                  } 
          catch (Exception e) {
                      e.printStackTrace();
                  }
              }
                  
              
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  doPost(request, response);
              }
          }

          上面的注釋應該說得比較清楚了,DispatchServlet的作用就是解析URI中的ServletName,然后在文件mockStruts-config.xml中以此查找對應的Servlet類,然后用反射生成它的實例處理用戶請求.解析的過程借助了正則表達式,查找XML的過程借助了dom4j.

          mockStruts-config.xml文件內容如下:
          <?xml version="1.0" encoding="GBK"?>

          <servlets>
              
          <!-- 處理登錄的Servlet -->
              
          <servlet>
                  
          <name>login</name>
                  
          <class>com.sitinspring.action.LoginServlet</class>
              
          </servlet>
              
              
          <!-- 處理注冊的Servlet -->
              
          <servlet>
                  
          <name>register</name>
                  
          <class>com.sitinspring.action.RegisterServlet</class>
              
          </servlet>
              
              
          <!-- 處理翻頁的Servlet -->
              
          <servlet>
                  
          <name>ShowPage</name>
                  
          <class>com.sitinspring.action.ShowPageServlet</class>
              
          </servlet>
          </servlets>

          接下來諸個Servlet類處理請求沒有什么特別的,你想怎么處理就怎么處理,在下面的Servlet中是找出了提交的所有參數并在后即頁面中展示.
          package com.sitinspring.action;

          import java.util.Enumeration;
          import java.util.Hashtable;
          import java.util.Map;

          import javax.servlet.RequestDispatcher;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          /**
           * 用于登錄處理的Servlet
           * 
          @author sitinspring
           *
           * @date 2008-2-12
           
          */
          public class LoginServlet extends HttpServlet {
              
          private static final long serialVersionUID = 56890894234786L;

              
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  request.setCharacterEncoding(
          "UTF-8");
                  
                  Map
          <String,String> ht=new Hashtable<String,String>();
                  
                  
          // 取得輸入參數并存入哈希表
                  Enumeration params=request.getParameterNames();        
                  
          while(params.hasMoreElements()){
                      String key
          =(String)params.nextElement();            
                      String value
          =request.getParameter(key);
                      
                      ht.put(key, value);
                  }
                  
                  request.setAttribute(
          "ht", ht);

                  RequestDispatcher dispatcher 
          = request.getRequestDispatcher("/web/page/loginResult.jsp");
                  dispatcher.forward(request, response);
                  
          return;
              }
                  
              
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  doPost(request, response);
              }
          }

          顯示結果的jsp頁面代碼:
          <%@ page contentType="text/html; charset=UTF-8"%>
          <%@page language="java" import="java.util.Map"%>
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>"MockStruts"-loginResult頁面</title>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <script src="web/js/ajax.js" type="text/javascript"></script>
          <link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
              type
          ="text/css" />
          </head>

          <body>    
              
          <%
                  Map
          <String,String> ht=(Map<String,String>)request.getAttribute("ht");    
              
                  
          for(String key:ht.keySet()){
                      
          String value=ht.get(key);
                      
                      out.print(
          "<p>參數名:"+key+" 參數值:"+value+"</p>");
                  }
              
          %>
          </body>
          </html>

          轉發效果之一(通過form提交請求):



          轉發效果之二(通過鏈接提交請求):




          本文代碼下載(請在lib中加入dom4j-1.6.1.jar并載入到工程的庫中):
          http://www.aygfsteel.com/Files/sitinspring/MockStruts20080329004955.zip

          posted on 2008-03-29 00:31 sitinspring 閱讀(2461) 評論(2)  編輯  收藏 所屬分類: SSH

          評論

          # re: Struts的ActionServlet模擬實現[未登錄] 2008-04-03 16:25 CoderDream

          這個不錯,支持一下!  回復  更多評論   

          # re: Struts的ActionServlet模擬實現 2013-05-09 13:48 ily

          你好 這樣寫后如何處理并發問題.  回復  更多評論   

          sitinspring(http://www.aygfsteel.com)原創,轉載請注明出處.
          主站蜘蛛池模板: 钟山县| 油尖旺区| 荥阳市| 祁东县| 申扎县| 佛教| 磐石市| 天津市| 新昌县| 岢岚县| 漠河县| 沁水县| 龙岩市| 长治市| 玛沁县| 礼泉县| 贺州市| 香港| 鄂托克旗| 读书| 东乡县| 平谷区| 郑州市| 城口县| 英超| 正蓝旗| 鹰潭市| 南召县| 云龙县| 陇西县| 油尖旺区| 武冈市| 宜都市| 揭西县| 上思县| 长汀县| 磐石市| 东丽区| 富民县| 蒲江县| 巩义市|