欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久

打開(kāi)APP
userphoto
未登錄

開(kāi)通VIP,暢享免費電子書(shū)等14項超值服

開(kāi)通VIP
超輕量級MVC框架的設計和實(shí)現 (2)

在設計完API后,我們就需要實(shí)現這個(gè)MVC框架。MVC框架的核心是一個(gè)DispatcherServlet,用于接收所有的HTTP請求,并根據URL選擇合適的Action對其進(jìn)行處理。在這里,和Struts不同的是,所有的組件均被IoC容器管理,因此,DispatcherServlet需要實(shí)例化并持有Guice IoC容器,此外,DispatcherServlet還需要保存URL映射和Action的對應關(guān)系,一個(gè)Interceptor攔截器鏈,一個(gè)ExceptionResolver處理異常。DispatcherServlet定義如下:

package com.javaeedev.lightweight.mvc;

/**
 * Core dispatcher servlet.
 *
 * @author Xuefeng
 */
public class DispatcherServlet extends HttpServlet {

    private Log log = LogFactory.getLog(getClass());

    private Map<String, ActionAndMethod> actionMap;
    private Interceptor[] interceptors = null;
    private ExceptionResolver exceptionResolver = null;
    private ViewResolver viewResolver = null;

    private Injector injector = null; // Guice IoC容器

    ...
}

Guice的配置完全由Java 5注解完成,而在DispatcherServlet中,我們需要主動(dòng)從容器中查找某種類(lèi)型的Bean,相對于客戶(hù)端被動(dòng)地使用IoC容器(客戶(hù)端甚至不能感覺(jué)到IoC容器的存在),DispatcherServlet需要使用ServiceLocator模式主動(dòng)查找Bean,寫(xiě)一個(gè)通用方法:

private List<Key<?>> findKeysByType(Injector inj, Class<?> type) {
    Map<Key<?>, Binding<?>> map = inj.getBindings();
    List<Key<?>> keyList = new ArrayList<Key<?>>();
    for(Key<?> key : map.keySet()) {
        Type t = key.getTypeLiteral().getType();
        if(t instanceof Class<?>) {
            Class<?> clazz = (Class<?>) t;
            if(type==null || type.isAssignableFrom(clazz)) {
                keyList.add(key);
            }
        }
    }
    return keyList;
}

DispatcherServlet初始化時(shí)就要首先初始化Guice IoC容器:

public void init(ServletConfig config) throws ServletException {
    String moduleClass = config.getInitParameter("module");
    if(moduleClass==null || moduleClass.trim().equals(""))
        throw new ServletException("Cannot find init parameter in web.xml: <servlet>"
                + "<servlet-name>?</servlet-name><servlet-class>"
                + getClass().getName()
                + "</servlet-class><init-param><param-name>module</param-name><param-value>"
                + "put-your-config-module-full-class-name-here</param-value></init-param></servlet>");
    ServletContext context = config.getServletContext();
    // init guice:
    injector = Guice.createInjector(Stage.PRODUCTION, getConfigModule(moduleClass.trim(), context));
    ...
}

然后,從IoC容器中查找Action和URL的映射關(guān)系:

private Map<String, ActionAndMethod> getUrlMapping(List<Key<?>> actionKeys) {
    Map<String, ActionAndMethod> urlMapping = new HashMap<String, ActionAndMethod>();
    for(Key<?> key : actionKeys) {
        Object obj = safeInstantiate(key);
        if(obj==null)
            continue;
        Class<Action> actionClass = (Class<Action>) obj.getClass();
        Annotation ann = key.getAnnotation();
        if(ann instanceof Named) {
            Named named = (Named) ann;
            String url = named.value();
            if(url!=null)
                url = url.trim();
            if(!"".equals(url)) {
                log.info("Bind action [" + actionClass.getName() + "] to URL: " + url);
                // link url with this action:
                urlMapping.put(url, new ActionAndMethod(key, actionClass));
            }
            else {
                log.warn("Cannot bind action [" + actionClass.getName() + "] to *EMPTY* URL.");
            }
        }
        else {
            log.warn("Cannot bind action [" + actionClass.getName() + "] because no @Named annotation found in config module. Using: binder.bind(MyAction.class).annotatedWith(Names.named(\"/url\"));");
        }
    }
    return urlMapping;
}

我們假定客戶(hù)端是以如下方式配置Action和URL映射的:

public class MyModule implements Module {

    public void configure(Binder binder) {
        // bind actions:
        binder.bind(Action.class)
              .annotatedWith(Names.named("/start.do"))
              .to(StartAction.class);
        binder.bind(Action.class)
              .annotatedWith(Names.named("/register.do"))
              .to(RegisterAction.class);
        binder.bind(Action.class)
              .annotatedWith(Names.named("/signon.do"))
              .to(SignonAction.class);
        ...
    }
}

即通過(guò)Guice提供的一個(gè)注解Names.named()指定URL。當然還可以用其他方法,比如標注一個(gè)@Url注解可能更方便,下一個(gè)版本會(huì )加上。

Interceptor,ExceptionResolver和ViewResolver也是通過(guò)查找獲得的。

下面討論DispatcherServlet如何真正處理用戶(hù)請求。第一步是根據URL查找對應的Action:

String contextPath = request.getContextPath();
String url = request.getRequestURI().substring(contextPath.length());
if(log.isDebugEnabled())
    log.debug("Handle for URL: " + url);
ActionAndMethod am = actionMap.get(url);
if(am==null) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404 Not Found
    return;
}

沒(méi)找到Action就直接給個(gè)404 Not Found,找到了進(jìn)行下一步,實(shí)例化一個(gè)Action并填充參數:

// init ActionContext:
HttpSession session = request.getSession();
ServletContext context = session.getServletContext();

ActionContext.setActionContext(request, response, session, context);

// 每次創(chuàng )建一個(gè)新的Action實(shí)例:
Action action = (Action) injector.getInstance(am.getKey());
// 把HttpServletRequest的參數自動(dòng)綁定到Action的屬性中:
List<String> props = am.getProperties();
for(String prop : props) {
    String value = request.getParameter(prop);
    if(value!=null) {
        am.invokeSetter(action, prop, value);
    }
}

注意,為了提高速度,所有的set方法已經(jīng)預先緩存了,因此避免每次請求都用反射重復查找Action的set方法。

然后要應用所有的Interceptor以便攔截Action:

InterceptorChainImpl chains = new InterceptorChainImpl(interceptors);
chains.doInterceptor(action);
ModelAndView mv = chains.getModelAndView();

實(shí)現InterceptorChain看上去復雜,其實(shí)就是一個(gè)簡(jiǎn)單的遞歸,大家看InterceptorChainImpl代碼就知道了:

package com.javaeedev.lightweight.mvc;

/**
 * Used for holds an interceptor chain.
 *
 * @author Xuefeng
 */
class InterceptorChainImpl implements InterceptorChain {

    private final Interceptor[] interceptors;
    private int index = 0;
    private ModelAndView mv = null;

    InterceptorChainImpl(Interceptor[] interceptors) {
        this.interceptors = interceptors;
    }

    ModelAndView getModelAndView() {
        return mv;
    }

    public void doInterceptor(Action action) throws Exception {
        if(index==interceptors.length)
            // 所有的Interceptor都執行完畢:
            mv = action.execute();
        else {
            // 必須先更新index,再調用interceptors[index-1],否則是一個(gè)無(wú)限遞歸:
            index++;
            interceptors[index-1].intercept(action, this);
        }
    }
}

把上面的代碼用try ... catch包起來(lái),就可以應用ExceptionResolver了。

如果得到了ModelAndView,最后一步就是渲染View了,這個(gè)過(guò)程極其簡(jiǎn)單:

// render view:
private void render(ModelAndView mv, HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {
    String view = mv.getView();
    if(view.startsWith("redirect:")) {
        // 重定向:
        String redirect = view.substring("redirect:".length());
        response.sendRedirect(redirect);
        return;
    }
    Map<String, Object> model = mv.getModel();
    if(viewResolver!=null)
        viewResolver.resolveView(view, model, reqest, response);
}

最簡(jiǎn)單的JspViewResolver的實(shí)現如下:

package com.javaeedev.lightweight.mvc.view;

/**
 * Let JSP render the model returned by Action.
 *
 * @author Xuefeng
 */
public class JspViewResolver implements ViewResolver {

    /**
     * Init JspViewResolver.
     */
    public void init(ServletContext context) throws ServletException {
    }

    /**
     * Render view using JSP.
     */
    public void resolveView(String view, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(model!=null) {
            Set<String> keys = model.keySet();
            for(String key : keys) {
                request.setAttribute(key, model.get(key));
            }
        }
        request.getRequestDispatcher(view).forward(request, response);
    }
}

至此,MVC框架的核心已經(jīng)完成。

1。在A(yíng)ction里現在的屬性set支持是基本類(lèi)型和數組,但是在一般的應用中,可能是希望直接得到一個(gè)PO, 這個(gè)怎么實(shí)現
2。一個(gè)action怎么實(shí)現處理多個(gè)請求,打個(gè)比方,用戶(hù)注冊,有一個(gè)方法doRegister,還有一個(gè)方法,驗證這個(gè)用戶(hù)名是否存在,在前臺用ajax調用一次,doValidateUserName,這兩個(gè)方法都在一個(gè)signupAction里,我在例子和sourcecode里都沒(méi)有找到比較好的解決辦法,請教樓主。
3。Example提供的例子非常好,但是Transaction在action的這個(gè)粒度上interceptor,感覺(jué)不是很好,從分層的角度講,不利于封裝;是不是在business層會(huì )更好一點(diǎn)
xuefeng發(fā)表于07-12-24 09:42
1.得到所有屬性后,就可以在execute()方法中構造該Bean,不想設計成Struts的FormBean,配置特別麻煩

2.寫(xiě)一個(gè)MultiAction,根據某個(gè)參數action=register用反射調用doRegister()或doValidate()

3.為了演示Interceptor的用法,和Filter類(lèi)似,但是僅限于A(yíng)ction層,不包括Render View,事務(wù)具體在哪里開(kāi)要根據具體應用確定
bus387發(fā)表于07-12-24 11:19
1.得到所有屬性后,就可以在execute()方法中構造該Bean,不想設計成Struts的FormBean,配置特別麻煩
在execute里再構造Bean,當然也是可以,如可以用BeanUtils.setProperties(request, po);  要是框架能做到這些事情,就更完美了。我相信你一定能做到0配置,不需要再像Struts一樣有FormBean, 我當時(shí)為了0配置到Google搜索就找到這個(gè)框架的。

“2.寫(xiě)一個(gè)MultiAction,根據某個(gè)參數action=register用反射調用doRegister()或doValidate()”

Good Idea! 這樣做的話(huà),doRegister和doValidate需要傳入的參數和表單提交的數據是不一樣的,如果form里有20幾個(gè)參數,這20幾個(gè)參數都放在action里作為屬性,就不好區分doRegister和doValidate方法需要的了。

xuefeng發(fā)表于07-12-24 13:33
java作為靜態(tài)語(yǔ)言和ruby還是不一樣的,ruby可以來(lái)個(gè)execute(MyBean bean),但是java如果這樣搞就必須用反射,而且不能利用接口調用了,比較好的方式是定義一個(gè)setBean(MyBean bean),效果和多個(gè)setBeanProperty1(), setBeanProperty2()效果類(lèi)似

下個(gè)版本可以考慮在一個(gè)Action中定義多個(gè)executeXxx()方法,每個(gè)execute方法可以對應一個(gè)setXxx(MyBean bean),url默認映射為/baseUrl/xxx?params
freeren發(fā)表于07-12-28 14:53
樓主,今天一直在研讀你的代碼
然后跟我同事談了這事,我想問(wèn)下,velocity是不是不再發(fā)布了,聽(tīng)說(shuō)現地freemarker更多人使用,是不是這樣?
mdream發(fā)表于07-12-28 14:55
velocity 最近不是已經(jīng)發(fā)了1.5版本了.貌似現在進(jìn)度比以前快很多.APACHE頂級項目.
xuefeng發(fā)表于07-12-28 15:43
freemarker就是比velocity多一個(gè)格式化功能,其他都差不多,主要是velocity配置比較簡(jiǎn)單
freeren發(fā)表于07-12-28 18:20
謝謝兩位的分享,看來(lái)小弟還有很多東西需要學(xué)的。今天下午小弟測試了代碼結果,tomcat啟動(dòng)時(shí)總是出現這個(gè)錯誤:
2007-12-28 17:57:35,781 [main] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[
/light] - Servlet /light threw load() exception
java.lang.ClassNotFoundException: com.lightmvc.sample.SampleModule

--小弟把目錄改了,在class目錄下也有SampleModule的class文件,但為什么總是說(shuō)找不到呢?
freeren發(fā)表于07-12-28 18:23
對了,還有web.xml的
 <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.do</url-pattern>
        <dispatcher>REQUEST</dispatcher> 
    </filter-mapping>
也出現了以下的報錯信息:
Multiple annotations found at this line:
- The content of element type "filter-mapping" must match "(filter-name,
 (url-pattern|servlet-name))".
- Missing end tag "filter-mapping"
小弟把<dispatcher>REQUEST</dispatcher>注釋了就沒(méi)問(wèn)題了。請問(wèn)這如何解決!
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請點(diǎn)擊舉報。
打開(kāi)APP,閱讀全文并永久保存 查看更多類(lèi)似文章
猜你喜歡
類(lèi)似文章
SpringMVC攔截器(資源和權限管理)
SpringMvc和servlet簡(jiǎn)單對比介紹
看透 Spring MVC 源代碼分析與實(shí)踐——俯視 Spring MVC
過(guò)濾器和攔截器的比較及未登錄用戶(hù)權限限制的實(shí)現
SSH(Struts,Spring,Hibernate)和SSM(SpringMVC,Spring,MyBatis)的區別
json2.js json.jar - xiejiaohui - JavaEye技術(shù)網(wǎng)站
更多類(lèi)似文章 >>
生活服務(wù)
分享 收藏 導長(cháng)圖 關(guān)注 下載文章
綁定賬號成功
后續可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服

欧美性猛交XXXX免费看蜜桃,成人网18免费韩国,亚洲国产成人精品区综合,欧美日韩一区二区三区高清不卡,亚洲综合一区二区精品久久