今天写了一个过滤器demo,现在是解析actions.xml文件,得到action中的业务规则;不需要导入任何jar包
ActionFilter过滤器类:
package accp.com.xh.utils; import java.io.IOException; import java.io.InputStream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * 创建过滤器 * 前端控制器 接收所有参数;设置编码的格式;做登陆的控制拦截;分发请求 * @author xiaohua * */ public class ActionFilter implements Filter{ /** * tomcat启动时执行,只会执行一次; * 解析配置的规则文件 :actions.xml */ @Override public void init(FilterConfig config) throws ServletException { try { //得到action.xml文件 InputStream is = Thread.currentThread().getContextClassLoader() .getResourceAsStream("actions.xml"); //解析xml文件 Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(is); //获取action标签元素:<action name="pro_.*" class="XXXXXAction"> NodeList nodeList = document.getElementsByTagName("action"); for(int i = 0 ;i<nodeList.getLength();i++){ //解析action标签元素 Element actionElement = (Element)nodeList.item(i); String actionName = actionElement.getAttribute("name"); String actionClass = actionElement.getAttribute("class"); System.out.println("actionName属性:"+actionName); System.out.println("actionClass属性:"+actionClass); //获取result 标签元素 //<result name="reload" type="redirect">product</result> NodeList resultList = actionElement.getElementsByTagName("result"); for(int j=0;j<resultList.getLength();j++){ Element resultEl =(Element) resultList.item(j); String resultName = resultEl.getAttribute("name");//得到action.xml中的result name属性 String resultType = resultEl.getAttribute("type"); System.out.println("name属性:"+resultName); System.out.println("type属性:"+resultType); } } } catch (Exception e) { throw new RuntimeException("解析action.xml文件出错:"+e.getMessage()); } } /** * 每次请求都会执行的过滤器 ; * 根据请求的URL 找出对应处理的XXXaction,判断哪个方法处理 */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req =(HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; // resp.sendRedirect(""); } /** * 正常停止tomcat的时候执行,只会执行一次; * 销毁资源的操作, */ @Override public void destroy() { } }
actions.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!-- 定义业务规则 --> <actions> <action name="pro_.*" class="XXXXXAction"> <result name="list">/WEB-INF/view/list.jsp</result> <result name="edit" type="redirect">/WEB-INF/view/edit.jsp</result> <result name="reload" type="redirect">product</result> </action> </actions>
启动服务器时输出得到的元素值:
当然别忘记了在web.xml中配置映射指定到ActionFilter类中去;这样启动服务时才会有所输出。
原文:http://www.cnblogs.com/1246447850qqcom/p/4802898.html