我们知道,在Struts1.x中,大致的内部处理流程是这样的:ActionServlet作为中央处理器,它配置在Web.xml中,接受所有*.do的请求,然后解析URI,得到*.do中的*部分,即path,然后根据path在struts-config.xml中找到具体处理业务的Action以及与之配套的ActionForm和ActionForward,再根据Action的type用Java反射机制生成Action的实例进行具体业务处理,如果Action有ActionForm也会用反射机制生成form传递到函数execute中,该函数返回一个ActionForward对象给ActionServlet,如果它不是空,ActionServlet会从中取出URl进行页面跳转,否则不采取行动。
实际上,要抛开Struts框架,自己实现这样一套流程并不很困难,利用Servlet,正则表达式,XML解析,反射和BeanUtils的相关知识就能实现一个。这样不但能巩固相关知识点的掌握,也能对Struts框架有进一步的理解。下面就是我按自己的理解完成的Struts内部流程的具体实现,事先声明一下,Struts的源码我没有看过,其中具体的处理可能和其原本的处理不一致,有些能简化的部分就简化了,文中处理不正确的地方还请方家指出。
1.ActionServlet的配置。
ActionServlet是一个Servlet,它是Struts框架中的中央控制器,在App启动时即载入,所有*.do的请求都会发给它,然后再由它派发给具体的业务处理Action,在我的模拟实现工程中,它是这样配置的。
<?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-file-list>
<welcome-file>/web/page/first.jsp</welcome-file>
</welcome-file-list>

<!-- 总控Servlet -->
<servlet>
<servlet-name>DispatchServlet</servlet-name>
<servlet-class>
com.heyang.action.ActionServlet
</servlet-class>
<init-param>
<description>Configuration File</description>
<param-name>configFile</param-name>
<param-value>web-inf\struts-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>

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

在这个Web.xml中,在servlet-mapping节点设置了所有*.do的请求都发给com.heyang.action.ActionServlet进行处理;init-param节点指定了配置文件Struts-conifg.xml的位置;在load-on-startup节点中,让这个Servlet变成自启动Servlet,这样设置后,一旦WebApp被载入容器,它的init方法就会被容器调用,在这个方法中,我们要执行重要的处理--读取配置文件struts-config.xml.
2.配置文件的读取。
前面说了,ActionServlet的init方法中要读取配置文件,读取之前当然要找到文件的物理位置,这不难,先取得Webapp的物理路径再加上param-value指定的相对路径即可,代码如下:

public class ActionServlet extends HttpServlet
{
private static final long serialVersionUID = 56890894234786L;

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException
{
..
}
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException
{
doPost(request, response);
}

/** *//**
* 初始化,当容器加载Servlet时会首先调用这个函数
* 因为设置了Servlet的load-on-startup部分
*/

public void init() throws ServletException
{
// 通过ServletContext取得工程的绝对物理路径
ServletContext sct = getServletContext();
String realPath = sct.getRealPath("/");
// 通过ServletConfig实例取得初始化参数configFile
ServletConfig config=this.getServletConfig();
String strutsCfgFile=config.getInitParameter("configFile");
// 组合配置文件全物理路径
strutsCfgFile=realPath+strutsCfgFile;
System.out.println("配置文件Struts-config.xml全物理路径是"+strutsCfgFile);
// 读入配置文件
StrutsConfiger.readConfigFile(strutsCfgFile);
}
}
最后,将配置文件的全路径装配好后,交给StrutsConfiger类的静态函数readConfigFile进行处理。
StrutsConfiger类的readConfigFile的主要功能是从struts-config.xml读出Action及与之配套的ActionForm和ActionForward的信息,然后存放在一个哈希表中。代码如下:

/** *//**
* 读取filePathname指定的配置文件,找出其中Action,ActionForm和ActionForwad的信息
* 放入一个ActionBean对象中,最后将这些对象放入哈希表actionMap
* @param filePathname
*/

public static void readConfigFile(String filePathname)
{

try
{
File file = new File(filePathname);
SAXReader reader = new SAXReader();
Document document = reader.read(file);
Element root = document.getRootElement();
// 找到Action将要用到的ActionForm
Element formBeansElm=root.element("form-beans");
List formNodes=formBeansElm.elements("form-bean");
Map<String,String> formMap=new HashMap<String,String>();

for(Iterator it=formNodes.iterator();it.hasNext();)
{
Element formElm=(Element)it.next();
formMap.put(formElm.attributeValue("name"), formElm.attributeValue("type"));
}
// 找到各Action及其下的ActionForward
actionMap =new Hashtable<String,ActionBean>();
Element actionMappingsElm=root.element("action-mappings");
List actionNodes=actionMappingsElm.elements("action");

for(Iterator it=actionNodes.iterator();it.hasNext();)
{
Element actionElm=(Element)it.next();
ActionBean actionBean=new ActionBean();
actionBean.setPath(actionElm.attributeValue("path"));
actionBean.setType(actionElm.attributeValue("type"));
String formName=actionElm.attributeValue("name");

if(formName!=null)
{
actionBean.setName(formName);
actionBean.setFormType(formMap.get(formName));
}
// Forward部分

try
{
List forwardNodes=actionElm.elements("forward");

for(Iterator iter=forwardNodes.iterator();it.hasNext();)
{
Element forwardElm=(Element)iter.next();

if(forwardElm!=null)
{
ForwardBean bean=new ForwardBean();
bean.setName(forwardElm.attributeValue("name"));
bean.setPath(forwardElm.attributeValue("path"));
actionBean.addForward(bean);
}
}
}

catch(Exception ex)
{
;// 如果这里发生异常,说明Action节点中没有forward子节点
}
actionMap.put(actionBean.getPath(), actionBean);
System.out.println(actionBean);
}

} catch (Exception ex)
{
throw new ReadStrutsCofigException("在使用dom4j阅读解析文档struts-config.xml时发生异常");
}
}
这段代码就是利用dom4j在Dom找到相应节点,有些特殊的地方如Action中可以有多个Forward或没有Forword需要注意一下,做一点特殊处理。
该函数执行完成后,配置文件的Action信息就被读入了StrutsConfiger的静态属性actionMap中,在处理具体用户请求时我们将会用到它。
3.将用户请求发给具体的Action。
在Web.xml中,所有*.do的请求都被发给了ActionServlet,我们需要解析出*部分,再根据它找到具体处理的Action。解析使用正则表达式即可,代码如下:
// 取得请求的URI
String reqUri=request.getRequestURI();
// 取得模式匹配字符串,即go,do等
String patternStr;

if(reqUri.contains("?"))
{
patternStr=StringUtil.getMatchedString("([.])(.*)?",reqUri);
}

else
{
patternStr=StringUtil.getMatchedString("([.])(.*)$",reqUri);
}

// 取得请求的path
String requestPath=StringUtil.getMatchedString("/(.*)(/.*)[.]"+patternStr,reqUri);
System.out.println("请求的path是"+requestPath);
辅助函数getMatchedString:

public static String getMatchedString(String regex,String text)
{
Pattern pattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Matcher matcher=pattern.matcher(text);

while(matcher.find())
{
return matcher.group(2);
}
return null;
}
解析出requestPath之后,我们使用StrutsConfiger类的函数getActionBean就可以找到与之对应的ActionBean,在这个bean中,负责具体进行处理的Action路径,ActionForm名和路径,ActionForward等信息都包含到了这个bean中。
接下来按流程进行处理,下面的代码中注释写得很清楚,这里就不赘述了。值得一提的是在向ActionForm的属性赋值时,Apche的工具类BeanUtils的使用,有了它的帮助,向一个实例的属性赋值顿时变得轻松容易起来,全要自己靠反射去实现就太耗功夫了。
// 找到处理这个请求的Action
ActionBean actionBean=StrutsConfiger.getActionBean(requestPath);

if(actionBean==null)
{
throw new CannotFindActionException("找不到path"+requestPath+"对应的Action");
}
System.out.println("处理请求的Action具体信息是"+actionBean);
// 通过反射调用真正的Action类进行处理
String actionClassName=actionBean.getType();

try
{
Class cls = Class.forName(actionClassName);
Action action = (Action)cls.newInstance();
// 找到Action中的Form
ActionForm form=null;

if(actionBean.getFormType()!=null)
{
Class cls2 = Class.forName(actionBean.getFormType());
form=(ActionForm)cls2.newInstance();
// 取得输入参数并存入哈希表
Enumeration params=request.getParameterNames();

while(params.hasMoreElements())
{
String key=(String)params.nextElement();
String value=request.getParameter(key);
BeanUtils.setProperty(form, key, value);
}
}
// 执行业务操作
ActionForward actionForward = action.execute(StrutsConfiger.getMappin(requestPath), form, request, response);
// 根据返回的actionForward翻页

if(actionForward!=null)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(actionForward.toString());
dispatcher.forward(request, response);
return;
}
}

catch (ClassNotFoundException e)
{
throw new ReflectionException("无法通过反射的方式生成"+actionClassName+"的实例");
}

catch (Exception e)
{
throw new UnexpectedException("未预料到的异常"+e.getMessage());
}
到这里,主要工作就已经完成了。
4.具体的Action示例。
下面是有ActionForm的Action。
package com.heyang.action;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heyang.action.base.Action;
import com.heyang.action.base.ActionForm;


/** *//**
* 用于登录处理的Servlet
* @author sitinspring
*
* @date 2008-2-12
*/

public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)

throws Exception
{
request.setCharacterEncoding("UTF-8");
Map<String,String> ht=new LinkedHashMap<String,String>();
LoginForm inform=(LoginForm)form;
ht.put("Name:", inform.getName());
ht.put("Pswd:", inform.getPswd());
request.setAttribute("ht", ht);

return mapping.findForward("loginResult");
}
}

下面是不需要ActionForm的Action:
package com.heyang.action;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heyang.action.base.Action;
import com.heyang.action.base.ActionForm;


/** *//**
* 用于页面跳转处理的Servlet
* @author sitinspring
*
* @date 2008-2-12
*/

public class ShowPageAction extends Action
{
private static final long serialVersionUID = 56890894234786L;

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

throws Exception
{
request.setCharacterEncoding("UTF-8");
String pageName=request.getParameter("page");
Map<String,String> ht=new LinkedHashMap<String,String>();
ht.put("无", "无");
request.setAttribute("ht", ht);

return new ActionForward("/web/page/"+pageName+".jsp");
}
}

可以看出,这和Struts的Action写法几乎是完全一样的。
到这里,Struts内部流程模拟实现的主要细节就写完了,有些代码在工程里,如果有兴趣可以下载来看看。
Sturts模拟工程代码下载:
http://www.blogjava.net/Files/heyang/StrutsFlowSimulator.rar