• struts过滤器的原理


    struts就是充当拦截器(过滤器)的作用。在web.xml配置过滤器,

      1 package cn.itcast.framework.core;
      2 
      3 import java.io.IOException;
      4 import java.lang.reflect.Method;
      5 import java.util.HashMap;
      6 import java.util.List;
      7 import java.util.Map;
      8 
      9 import javax.servlet.Filter;
     10 import javax.servlet.FilterChain;
     11 import javax.servlet.FilterConfig;
     12 import javax.servlet.ServletException;
     13 import javax.servlet.ServletRequest;
     14 import javax.servlet.ServletResponse;
     15 import javax.servlet.http.HttpServletRequest;
     16 import javax.servlet.http.HttpServletResponse;
     17 
     18 import org.apache.commons.beanutils.BeanUtils;
     19 import org.dom4j.Document;
     20 import org.dom4j.Element;
     21 
     22 import cn.itcast.framework.util.Dom4JUtil;
     23 
     24 public class CenterFilter implements Filter {
     25     //存取配置文件信息。key:对应action中的name value:Action对象
     26     private Map<String, Action> actions = new HashMap<String, Action>();
     27     private FilterConfig filterConfig;
     28     
     29     public void init(FilterConfig filterConfig) throws ServletException {
     30         initCfg();//初始化配置文件
     31         this.filterConfig = filterConfig;
     32         
     33     }
     34     //初始化配置文件
     35     private void initCfg() {
     36         //读取XML配置文件:把配置文件中的信息封装到对象中.再放到actions中
     37         
     38         Document document = Dom4JUtil.getDocument();
     39         Element root = document.getRootElement();
     40         //得到所有的action元素,创建Action对象,封装信息
     41         List<Element> actionElements = root.elements("action");
     42         if(actionElements!=null&&actionElements.size()>0){
     43             for(Element actionElement:actionElements){
     44                 //封装action信息开始
     45                 Action action = new Action();
     46                 action.setName(actionElement.attributeValue("name"));
     47                 action.setClassName(actionElement.attributeValue("class"));
     48                 String methodXmlAttrValue = actionElement.attributeValue("method");
     49                 if(methodXmlAttrValue!=null)
     50                     action.setMethod(methodXmlAttrValue);
     51                 //封装action信息结束
     52                 
     53                 
     54                 //得到每个action元素中的result元素,创建Result对象,封装信息
     55                 //封装属于当前action的结果
     56                 List<Element> resultElements = actionElement.elements("result");
     57                 if(resultElements!=null&&resultElements.size()>0){
     58                     for(Element resultElement:resultElements){
     59                         Result result = new Result();
     60                         result.setName(resultElement.attributeValue("name"));
     61                         result.setTargetUri(resultElement.getText().trim());
     62                         String typeXmlValue = resultElement.attributeValue("type");
     63                         if(typeXmlValue!=null){
     64                             result.setType(ResultType.valueOf(typeXmlValue));
     65                         }
     66                         action.getResults().add(result);
     67                     }
     68                 }
     69                 //封装属于当前action的结果
     70                 
     71                 
     72                 
     73                 //把Action对象都放到Map中
     74                 actions.put(action.getName(), action);
     75             }
     76         }
     77     }
     78     public void doFilter(ServletRequest req, ServletResponse resp,
     79             FilterChain chain) throws IOException, ServletException {
     80         try {
     81             HttpServletRequest request = (HttpServletRequest)req;
     82             HttpServletResponse response = (HttpServletResponse)resp;
     83             //真正的控制器部分
     84             
     85             //取一个配置参数
     86             String aciontPostFixs [] = {"action","","do"};//你请求的地址以actiondo空结尾的话,才真正过滤。默认值
     87             String aciontPostFix = filterConfig.getInitParameter("aciontPostFix");
     88             if(aciontPostFix!=null){
     89                 aciontPostFixs = aciontPostFix.split("\,");
     90             }
     91             
     92             //解析用户请求的URI
     93             String uri = request.getRequestURI();//   /strutsDay01MyFramework/addCustomer.action
     94             
     95             //截取后缀名,看看是否需要我们的框架进行处理
     96             //切后缀名
     97             String extendFileName = uri.substring(uri.lastIndexOf(".")+1);// /strutsDay01MyFramework/addCustomer.action   action
     98                                                                             // 
     99 
    100 /strutsDay01MyFramework/addCustomer.do   do
    101                                                                             // 
    102 
    103 /strutsDay01MyFramework/addCustomer   ""
    104             boolean needProcess = false;
    105             for(String s:aciontPostFixs){
    106                 if(extendFileName.equals(s)){
    107                     needProcess = true;
    108                     break;
    109                 }
    110             }
    111             
    112             if(needProcess){
    113                 //需要框架处理
    114                 //解析uri中的动作名称
    115                 String requestActionName = uri.substring(uri.lastIndexOf("/")+1, uri.lastIndexOf("."));
    116                 System.out.println("您的请求动作名是:"+requestActionName);
    117                 //查找actions中对应的Action对象
    118                 if(actions.containsKey(requestActionName)){
    119                     Action action = actions.get(requestActionName);
    120                     //得到类名称的字节码
    121                     Class clazz = Class.forName(action.getClassName());
    122                     //封装数据到JavaBean中,利用BeanUtils框架
    123                     Object bean = clazz.newInstance();
    124                     BeanUtils.populate(bean, request.getParameterMap());
    125                     //实例化,调用其中指定的方法名称
    126                     Method m = clazz.getMethod(action.getMethod(), null);
    127                     //根据方法的返回值,遍历结果
    128                     String resultValue = (String)m.invoke(bean, null);
    129                     
    130                     List<Result> results = action.getResults();
    131                     if(results!=null&&results.size()>0){
    132                         for(Result result:results){
    133                             
    134                             if(resultValue.equals(result.getName())){
    135                                 //根据结果中的type决定是转发还是重定向
    136                                 //重定向的目标就是结果中的targetUri
    137                                 if("dispatcher".equals(result.getType().toString())){
    138                                     //转发
    139                                     request.getRequestDispatcher(result.getTargetUri()).forward(request, response);
    140                                 }
    141                                 if("redirect".equals(result.getType().toString())){
    142                                     //重定向
    143                                     response.sendRedirect(request.getContextPath()+result.getTargetUri());
    144                                 }
    145                             }
    146                         }
    147                     }
    148                 }else{
    149                     throw new RuntimeException("The action "+requestActionName+" is not founded in your config files!");
    150                 }
    151                 
    152             }else{
    153                 chain.doFilter(request, response);
    154             }
    155         } catch (Exception e) {
    156             throw new RuntimeException(e);
    157         }
    158         
    159     }
    160 
    161     public void destroy() {
    162 
    163     }
    164 
    165 }

    此过滤器初始化的时候读取 默认src下 自己定义的名字 .xml文件,根据dom4j解析,取出配置信息,实例化对象。在doFilter中过滤请求。实质就是配置 .xml文件然后 读取文件进行配置。

  • 相关阅读:
    BZOJ1222: [HNOI2001]产品加工(诡异背包dp)
    洛谷P1208 [USACO1.3]混合牛奶 Mixing Milk(贪心)
    SDOI 2018划水记
    【Leetcode】Search in Rotated Sorted Array II
    HDU 4089 Activation
    linux scp ssh命令不用输入密码
    封装fastjson为spring mvc的json view
    codility上的练习(3)
    git 拉取远程分之到本地
    Oracle 索引扫描的4种类型
  • 原文地址:https://www.cnblogs.com/friends-wf/p/3765326.html
Copyright © 2020-2023  润新知