承接上文,所有自定义的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是干什么的呢,我们去下一节。