1. 程式人生 > >一步一步寫一個java web開發框架(4)

一步一步寫一個java web開發框架(4)

承接上文,所有自定義的Action都已經獲取到了,那麼下一步做什麼呢?

找到與使用者輸入連結相匹配的Action,然後執行Action的method方法,就可以輸出結果了。

修改StrutsFilter的doFilter方法

@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 設定編碼
		request.setCharacterEncoding(STR.ENCODING_UTF8);
		response.setCharacterEncoding(STR.ENCODING_UTF8);

		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		ActionMapper action = this.context.getActionMapper(path);
		if (action != null) {
			logger.debug("Find the action " + path);
			action.execute(req, (HttpServletResponse) response);
		} else {
			logger.debug("Not found the action " + path);
			chain.doFilter(request, response);
		}
	}

StrutsContext裡查詢Action的函式

public ActionMapper getActionMapper(String path) {
		return actionList.get(path);
	}

這樣找到ActionMapper然後執行execute函式,就會輸出結果

public class ActionMapper {
	private static final Logger logger = Logger.getLogger(ActionMapper.class);

	private Method method;

	public ActionMapper(Method method) {
		this.method = method;
	}

	public void execute(HttpServletRequest request, HttpServletResponse response) {
		try {
			Object bean = this.method.getDeclaringClass().newInstance();
			Object result = this.method.invoke(bean);
			if (result != null) {
				ResponseWrapper wrapper = new ResponseWrapper(request, response);
				wrapper.doResponse(result);
			}
		} catch (Exception e) {
			logger.error("Execute action faild", e);
		}
	}

}

那麼execute中的ResponseWrapper是幹什麼的呢,我們去下一節。