Ruby on Rails有個設計思想是:用編碼規定代替繁瑣的配置文件。jvm平臺已經有一些類似ror的實現,比如
grails:http://docs.codehaus.org/display/GRAILS/2006/03/29/Groovy+on+Rails+(Grails)+0.1+Released
雖然由于java自身的局限,它很難做出像ruby或者groovy那樣動態語言那樣隨心所欲的動作,但是利用它的運行時反射、動態代理等特性來盡可能體現“用編碼規定代替繁瑣的配置文件”這一思想。下面就轉入正題。
ServletAPI對HTTP協議進行了封裝,通過配置Web.xml來把不同的請求轉發給不同的servlet來處理。Web框架則用一個ActionServlet,根據自己的對Action的定義來轉發請求。
拋開那些繁瑣的配置文件,設想一下這樣一種方法:
1.Web動作的處理和響應
假設這樣一個POST請求:
<
form?
action
="logic/group/NewTopic"
?method
="post"
>
Web動作實現Bean:
org.qqsns.web.logic.group.NewTopic
注意后面的logic/group/NewTopic和logic.group.NewTopic, 動作類和Web動作是通過請求路徑和包名相互關聯。
這樣,對Web動作的響應就依賴于編譯期的代碼的組織結構而不是執行期的配置文件。這樣的好處是避免了維護繁瑣的配置文件,特別是在沒有IDE支持的情況下。
org.qqsns.web.logic.group.NewTopic類是一個實現net.wff.servlet.WebAction接口的POJO,下面是NewTopic中execute的方法片段:???
//
Only?method?must?be?implemented?for?interface?net.wff.servlet.WebAction
?
public
?String?execute(HttpServletRequest?request,?HttpServletResponse?response)

?
throws
?ServletException,?IOException
{
??
??
//
return?"redirect?/success.html";??
//
請求重定向
??
return
?
"
/success.jsp
"
;??????????????
//
請求轉發
}
?execute方法的返回值手動指定了一個轉發或重定向的路徑。
2.輸入驗證
普通的Web框架都帶數據輸入驗證功能,一般復雜程度和功能強大與否成正比。
這里簡單地要求從setter方法里拋出一個包含驗證信息的異常,以此來實現輸入異常處理。
??????
普通setter方法
public
?
void
?setName(String?name)
{?
??
this
.name?
=
?name;
}
添加輸入驗證后的setter方法
public
?
void
?setName(String?name)?
throws
?InputException
{????
?
if
(name.length()
<
3
)
????
throw
?
new
?InputException(
"
Topic?name?must?has?a?length?greater?than?3
"
);?
??
this
.name?
=
?name;
}
WaterFallServlet是如何處理驗證信息的:
WebAction?wa?
=
?
????(WebAction)Class.forName(classPath).newInstance();
??????????
//
procces?forwarding
??????????
try
?
{
????ActionHelper.setProperties(request,wa);

???}
?
catch
?(InputException?e)?
{
????
//
return?to?input?view
????
//
header:referer
????String?rtn?
=
?request.getHeader(
"
referer
"
);
????
//
clear?old?errors
????
if
(rtn.indexOf(
"
?
"
)
!=
1
)
{
?????rtn?
=
?rtn.substring(
0
,rtn.indexOf(
"
?
"
));
????}
????rtn
=
rtn
+
"
?error=
"
+
URLEncoder.encode(e.getMessage(),
"
UTF-8
"
);
????response.sendRedirect(rtn);
????
return
;
???}
這樣驗證信息通過請求參數傳回到輸入頁面.
3.數據綁定
假設有這樣的html輸入:?
<
input?
type
="text"
?name
="name"
/>
<
input?
type
="text"
?name
="number"
/>
<
input?
type
="text"
?name
="price"
/>
?下面是NewTopic中execute的方法全部:???
public
?String?execute(HttpServletRequest?request,?HttpServletResponse?response)

?
throws
?ServletException,?IOException
{
??System.out.println(getName());
??System.out.println(getNumber());
??System.out.println(getPrice());
??System.out.println(getLength());
??
return
?
"
/success.html
"
;
}
自動從request注入parameter,這也許是很多人喜歡Struts DynamicActionForm的原因之一。
不過這里實現更類似多了類型轉換的<jsp:setProperty name="bean" property="*"/>
因為Name的類型是String,Number的類型是Integer,Price的類型是float,length的類型是double.至于其他復雜的類型,也許jsf的轉換器是個更好的主意。
這樣就初步解決了數據的輸入綁定和驗證。余下的就是業務邏輯的問題。WaterfallWebFramework源代碼:
http://m.tkk7.com/Files/zqc/WaterfallWebFramework.rar?(只有一個配置文件,其中只有1行配置信息!)
以上就是框架的主要功能。用編碼規定代替配置文件,也許這會是一種更加高效率的開發方式。