struts2源码分析之获取请求uri,ActionMapping的封装

struts2当请求一个action时:

直接进入:StrutsPrepareAndExecuteFilter的doFilter所以struts2是基于拦截器实现的。

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        try {
            prepare.setEncodingAndLocale(request, response);
            prepare.createActionContext(request, response);
            prepare.assignDispatcherToThread();
			if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
				chain.doFilter(request, response);
			} else {
				request = prepare.wrapRequest(request);
				//根据请求的uri封装为一个ActionMapping ActionMapping源码如下:
				/* public class ActionMapping {

                                  private String name;
                                  private String namespace;
                                  private String method;
                                  private String extension;
                                  private Map<String, Object> params;
                                  private Result result;
				*/
				//这个方法里面有一步判断如果不是以<constant name="struts.action.extension" value="do,action,"></constant>中的配置结尾的mapping就会为null
				//就会直接放行该方法源码如下:
				/**
				  protected String dropExtension(String name, ActionMapping mapping) {
        if (extensions == null) {
            return name;
        }
        for (String ext : extensions) {
            if ("".equals(ext)) {
                // This should also handle cases such as /foo/bar-1.0/description. It is tricky to
                // distinquish /foo/bar-1.0 but perhaps adding a numeric check in the future could
                // work
                int index = name.lastIndexOf('.');
                if (index == -1 || name.indexOf('/', index) >= 0) {
                    return name;
                }
            } else {
                String extension = "." + ext;
                if (name.endsWith(extension)) {
                    name = name.substring(0, name.length() - extension.length());
                    mapping.setExtension(ext);
                    return name;
                }
            }
        }
        return null;
				*/
				ActionMapping mapping = prepare.findActionMapping(request, response, true);
				//判断mapping如果为空,放行
				if (mapping == null) {
					boolean handled = execute.executeStaticResourceRequest(request, response);
					if (!handled) {
						chain.doFilter(request, response);
					}
				} else {
					//进入主要拦截方法了
					execute.executeAction(request, response, mapping);
				}
			}
        } finally {
            prepare.cleanupRequest(request);
        }
    }

相关推荐