我見過許多項目開發(fā)者實現(xiàn)自己專有的MVC框架。這些開發(fā)者并不是因為想實現(xiàn)不同于Struts的某些功能,而是還沒有意識到怎么去擴展Struts。通過開發(fā)自己的MVC框架,你可以掌控全局,但同時這也意味著你必須付出很大的代價;在項目計劃很緊的情況下也許根本就不可能實現(xiàn)。
Struts不但功能強大也易于擴展。你可以通過三種方式來擴展Struts:
1.PlugIn:在應用啟動或關閉時須執(zhí)行某業(yè)務邏輯,創(chuàng)建你自己的PlugIn類
2.RequestProcessor:在請求處理階段一個特定點欲執(zhí)行某業(yè)務邏輯,創(chuàng)建你自己的RequestProcessor。例如:你想繼承RequestProcessor來檢查用戶登錄及在執(zhí)行每個請求時他是否有權限執(zhí)行某個動作。
3.ActionServlet:在應用啟動或關閉或在請求處理階段欲執(zhí)行某業(yè)務邏輯,繼承ActionServlet類。但是必須且只能在PligIn和RequestProcessor都不能滿足你的需求時候用。
本文會列舉一個簡單的Struts應用來示范如何使用以上三種方式擴展Struts。在本文末尾資源區(qū)有每種方式的可下載樣例源代碼。Struts Validation 框架和 Tiles 框架是最成功兩個的Struts擴展例子。
我是假設讀者已經(jīng)熟悉Struts框架并知道怎樣使用它創(chuàng)建簡單的應用。如想了解更多有關Struts的資料請參見資源區(qū)。
PlugIn
根據(jù)Struts文檔,“PlugIn是一個須在應用啟動和關閉時需被通知的模塊定制資源或服務配置包”。這就是說,你可以創(chuàng)建一個類,它實現(xiàn)PlugIn的接口以便在應用啟動和關閉時做你想要的事。
假如創(chuàng)建了一個web應用,其中使用Hibernate做為持久化機制;當應用一啟動,就需初始化Hinernate,這樣在web應用接收到第一個請求時,Hibernate已被配置完畢并待命。同時在應用關閉時要關閉Hibernate。跟著以下兩步可以實現(xiàn)Hibernate PlugIn的需求。
1.創(chuàng)建一個實現(xiàn)PlugIn接口的類,如下:
public class HibernatePlugIn implements PlugIn{
private String configFile;
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering HibernatePlugIn.destroy()");
//Put hibernate cleanup code here
System.out.println("Exiting HibernatePlugIn.destroy()");
}
//This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering HibernatePlugIn.init()");
System.out.println("Value of init parameter " +
getConfigFile());
System.out.println("Exiting HibernatePlugIn.init()");
}
public String getConfigFile() {
return name;
}
public void setConfigFile(String string) {
configFile = string;
}
}
<struts-config>
...
<!-- Message Resources -->
<message-resources parameter=
"sample1.resources.ApplicationResources"/>
<!-- Declare your plugins -->
<plug-in className="com.sample.util.HibernatePlugIn">
<set-property property="configFile"
value="/hibernate.cfg.xml"/>
</plug-in>
</struts-config>
public void process(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will
// use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested
processLocale(request, response);
// Set the content type and no-caching headers
// if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
// Identify the mapping for this request
ActionMapping mapping =
processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form =
processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to
// process this request
Action action =
processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}
<controller>
<set-property property="locale" value="false"/>
</controller>
<controller>
<set-property property="contentType" value="text/plain"/>
</controller>
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 1);
<controller>
<set-property property="noCache" value="true"/>
</controller>
<action path="/newcontact" type="com.sample.NewContactAction"
name="newContactForm" scope="request">
<forward name="sucess" path="/sucessPage.do"/>
<forward name="failure" path="/failurePage.do"/>
</action>
<form-bean name="newContactForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="firstName"
type="java.lang.String"/>
<form-property name="lastName"
type="java.lang.String"/>
</form-bean>
<action forward="/Login.jsp" path="/loginInput"/>
<action include="/Login.jsp" path="/loginInput"/>
public class CustomRequestProcessor
extends RequestProcessor {
protected boolean processPreprocess (
HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}
protected void processContent(HttpServletRequest request,
HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}
<controller>
<set-property property="processorClass"
value="com.sample.util.CustomRequestProcessor"/>
</controller>
<web-app >
<servlet>
<servlet-name>action=</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<!-- All your init-params go here-->
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app >
只有注冊用戶登錄后才能發(fā)表評論。 | ||
![]() |
||
網(wǎng)站導航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||
相關文章:
|
||