Struts、Ajax、Restful、Web Service 狂想曲框架兑现篇(二)

Struts、Ajax、Restful、Web Service 狂想曲框架实现篇(二)?@Overridepublic void init(FilterConfig config)

Struts、Ajax、Restful、Web Service 狂想曲框架实现篇(二)

?

@Overridepublic void init(FilterConfig config) throws ServletException {application = config.getServletContext();String loadPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();String classPath = loadPath.substring(1, loadPath.length());ArrayList<String> actions = XMLReader.getNodeValues(classPath + "unicorn-config.xml", "actions");this.initActions(actions);ArrayList<String> routers = XMLReader.getNodeValues(classPath + "unicorn-config.xml", "routers");this.initRouters(routers);}?@Override

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;String path = request.getContextPath();String uri = request.getRequestURI();String relativeUri = uri.substring(path.length(), uri.length());this.request = request;this.session = request.getSession();this.response = (HttpServletResponse) servletResponse;// 用户自定义的Router优先级最高,url先通过用户定义的Iterator<IPathRouter> iterator = routerList.iterator();while(iterator.hasNext()) {IPathRouter router = iterator.next();if(router.route(relativeUri, this)) {return ;}}// 拦截不到的继续访问filterChain.doFilter(servletRequest, servletResponse);}
?private void initRouters(ArrayList<String> routers) {routerList = new ArrayList<IPathRouter>();for (int i = 0; i < routers.size(); i++) {String routerName = routers.get(i);try {Class<?> clz = Class.forName(routers.get(i));// 单例模式通过方法获取对象实例IPathRouter router = (IPathRouter) clz.newInstance();routerList.add(router);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}}// 最后把框架默认的Router加入进来routerList.add(new AMPPathRouter());}?

   ? ? ?其中unicorn-config.xml文件的编写,拿其中我一个项目里的这个文件来举例:

?><config> <routers> <router class="com.mh.router.MySessionCheckRouter"></router> </routers> <actions> <action class="com.mh.action.UserAction"></action> <action class="com.mh.action.InformationAction"></action> <action class="com.mh.action.UploadInformationIconAction"></action> <action class="com.mh.action.TempPicAction"></action> <action class="com.mh.action.MobileAction"></action> </actions></config>

? ? ? 这里即定义了Action,也定义了自己的Router,并且从名称上可以看出,这个SessionCheckRouter是要判断所有提交到服务器的指定url的请求 是否已经登录过,没有登录,可能会把此请求遣送会登录页。以及初始化所有的Action,在Router处理完请求,分发给action时,可以从filter里面去取。