好,承接上文。StrutsFilter实现自servlet的Filter接口。
init函数,需要做一些初始化操作,比如实例化StrutsContext。
@Override
public void init(FilterConfig filterConfig) throws ServletException {
context = new StrutsContext(filterConfig.getServletContext());
logger.debug("init");
}
doFilter是具体查找Action并分析执行的方法。通过RequestMapping配置的链接和当前链接比较,最后找到要执行的函数,进行response处理。
@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);
}
}
destroy会将StrutsContext清空并销毁,不会因缓存等问题和下一次初始化产生冲突。
@Override
public void destroy() {
if (context != null) {
context.clear();
context = null;
}
logger.debug("des");
}
总而言之,init执行后,项目的配置和链接都已加载完毕,然后就是每个链接的具体调用。
StrutsContext,到底做了些什么,请看下一节。一步一步写一个java web开发框架(3)