`
wkrain
  • 浏览: 6427 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

课堂上讲课时写的一个简单的仿struts2框架

    博客分类:
  • java
阅读更多
课堂上讲课时写的一个简单的仿struts2框架

package intecerptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import struts.Action;

/**
*
* @author Administrator
*/
public interface  ActionInvocation {
  public Action getAction() ;
  public String invoke() throws Exception;;
     public HttpServletRequest getRequest() ;
    public HttpServletResponse getResponse();
    public boolean isValidate();
     public void setValidation(boolean v);
}



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package intecerptor;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import struts.Action;

/**
*
* @author Administrator
*/
public class DefaultActionInvocation implements ActionInvocation {
    private Action action;

   private  HttpServletRequest request;
   private HttpServletResponse response;

    public DefaultActionInvocation(HttpServletRequest request, HttpServletResponse response) {
       this.request=request;
       this.response=response;
    }
    public Action getAction() {
       return action;
    }

    public void setAction(Action action){
        this.action=action;
    }

    List<Interceptor> interceptors=new ArrayList<Interceptor>();

    public void addInterceptor(Interceptor interceptor){
        interceptors.add(interceptor);
    }
    private int index=-1;
    private  String result="";
    public String invoke() throws Exception{
      if(index==interceptors.size()-1){
          if(this.isValidate())
              result=action.execute();
          else
             result=Action.INPUT;
      }else{
          index++;
          ((Interceptor)interceptors.get(index)).interceptor(this);
      }

      return result;

    }

    /**
     * @return the request
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * @return the response
     */
    public HttpServletResponse getResponse() {
        return response;
    }

    public boolean isValidate() {
        return v;
    }

    private boolean v;
    public void setValidation(boolean v){
        this.v=v;
    }
   
}




/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package intecerptor;

/**
*
* @author Administrator
*/
public abstract class DefaultInterceptor  implements Interceptor{

    public void destory() throws Exception {
    }

    public void init() throws Exception {      
    }

}



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package intecerptor;

/**
*
* @author Administrator
*/
public interface  Interceptor {
      public void init() throws Exception;
      public void destory() throws Exception;
      public String interceptor(ActionInvocation  actionInvocation) throws Exception;

}



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package intecerptor;

import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;

/**
*
* @author Administrator
*/
public class ParamInterceptor extends DefaultInterceptor {

    public String interceptor(ActionInvocation actionInvocation) throws Exception {
        BeanUtils.populate(actionInvocation.getAction(), actionInvocation.getRequest().getParameterMap());
        String result = actionInvocation.invoke();
        Map param = BeanUtils.describe(actionInvocation.getAction());
        param.remove("class");
        for (Iterator it = param.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            actionInvocation.getRequest().setAttribute(key, param.get(key));
        }
        return result;
    }
}



package struts;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Administrator
*/
public interface Action {
    String SUCCESS="success";
    String INPUT ="input";
    String FAILED="failed";
   
   String execute() throws Exception;
}



package struts;


import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Administrator
*/
public class ActionFactory {

    public static Map<String ,XmlMapping>  actions;
 
    public static void initActions(InputStream input){
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(input);
            Element root=document.getRootElement();
            actions=new HashMap<String ,XmlMapping>();
            treeWalk(root,null);

        } catch (DocumentException ex) {
           ex.printStackTrace();
        }
        //
    }


    public static void treeWalk(Element element,XmlMapping xm) {
       for (int i = 0, size = element.nodeCount(); i < size; i++)     {
           Node node = element.node(i);
           if (node instanceof Element) {
                Element el=(Element)node;
               if("action".equals(node.getName())){
                   if(xm==null)
                       xm=new XmlMapping();

               
                 for(Iterator iter = el.attributeIterator(); iter.hasNext();) {
                       Attribute attribute = (Attribute) iter.next();
                       String attr=attribute.getName();
                       if("name".equals(attr)){
                           xm.setActionName(attribute.getValue());
                       }
                       if("type".equals(attr)){
                           xm.setActionType(attribute.getValue());
                       }

                 }
                    actions.put(xm.getActionName(),xm);
               }
               if("result".equals(node.getName())){
                    for(Iterator iter = el.attributeIterator(); iter.hasNext();) {
                       Attribute attribute = (Attribute) iter.next();
                       String attr=attribute.getName();
                       if("name".equals(attr)){
                            xm.getResults().put(attribute.getValue(),el.getText());
                       }


                 }
               }

              treeWalk((Element) node,xm);
           } else { // do something....
           }
       }
}


    public static String getResult(String actionName, String code){
        XmlMapping mp=(XmlMapping)actions.get(actionName);
        String result=mp.getResults().get(code);
        return result;
    }
    public static  Action createAction(String actionName,Map parameter){
         Action action=null;
         try {
            String type=((XmlMapping)actions.get(actionName)).getActionType();
            action=(Action) Class.forName(type).newInstance();
           BeanUtils.populate(action,parameter);
        } catch (Exception ex) {
           ex.printStackTrace();
        }
          return action;
    }

    public static void main(String[] args ){
        try {
            try {
                Action action = (Action) Class.forName("actions.LoginAction").newInstance();
                System.out.println(action);
            } catch (InstantiationException ex) {
                Logger.getLogger(ActionFactory.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(ActionFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ActionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import java.util.HashMap;
import java.util.Map;

/**
*
* @author Administrator
*/
public abstract class ActionSupport implements Action  ,Validator{
    protected String message;
    private Map<String,String> fieldErrors =new HashMap<String,String>();

    public abstract String execute() throws Exception ;

    public void validatoin() throws Exception {
    
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }
    public boolean isFieldErrors(){
        return !fieldErrors.isEmpty();
    }

    /**
     * @return the fieldErrors
     */
    public Map<String, String> getFieldErrors() {
        return fieldErrors;
    }

    /**
     * @param fieldErrors the fieldErrors to set
     */
    public void setFieldErrors(Map<String, String> fieldErrors) {
        this.fieldErrors = fieldErrors;
    }

    public void addFiledErrors(String key,String value){
        fieldErrors.put(key, value);
    }
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import java.util.Map;

/**
*
* @author Administrator
*/
public interface  ContextAware {
      void setContext(Map context);
      Map getContext();
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import java.util.Map;

/**
*
* @author Administrator
*/
public interface  RequestAware {
      void setRequest(Map request);
      Map getRequest();
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import java.util.Map;

/**
*
* @author Administrator
*/
public interface  SessionAware {
      void setSession(Map session);
      Map getSession();
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

/**
*
* @author Administrator
*/
public interface  Validator {

    void  validatoin() throws Exception;
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import java.util.HashMap;
import java.util.Map;

/**
*
* @author Administrator
*/
public class XmlMapping {
   private String actionName;
   private String actionType;
   private Map<String ,String>  results= new HashMap<String ,String>();;

    /**
     * @return the actionName
     */
    public String getActionName() {
        return actionName;
    }

    /**
     * @param actionName the actionName to set
     */
    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    /**
     * @return the actionType
     */
    public String getActionType() {
        return actionType;
    }

    /**
     * @param actionType the actionType to set
     */
    public void setActionType(String actionType) {
        this.actionType = actionType;
    }

    /**
     * @return the results
     */
    public Map<String, String> getResults() {
        return results;
    }

    /**
     * @param results the results to set
     */
    public void setResults(Map<String, String> results) {
        this.results = results;
    }
  

}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package struts;

import intecerptor.DefaultActionInvocation;
import intecerptor.LogInterceptor;
import intecerptor.ParamInterceptor;
import intecerptor.TimeInterceptor;
import intecerptor.ValidatorInterceptor;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

/**
*
* @author Administrator
*/
public class StrutsDispatcher extends HttpServlet {
  
  

  
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         doPost( request,  response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String next;
        String action=request.getRequestURI().replaceAll(request.getContextPath(), "");//login.action
        action=action.substring(1,action.lastIndexOf("."));//login
        if(action!=null&&!"".equals(action)){
            Action actionInstance =ActionFactory.createAction(action,request.getParameterMap());
            try {
                DefaultActionInvocation da=new DefaultActionInvocation(request,response);
                da.setAction(actionInstance);
                ParamInterceptor paramInterceptor=new ParamInterceptor();
                LogInterceptor log=new LogInterceptor();
                TimeInterceptor time=new TimeInterceptor();
                ValidatorInterceptor validator=new ValidatorInterceptor();
                da.addInterceptor(paramInterceptor);
               // da.addInterceptor(validator);
                da.addInterceptor(log);
                da.addInterceptor(time);

                 String  result=da.invoke();
                 result=ActionFactory.getResult(action, result);
                 request.getRequestDispatcher(result).forward(request, response);
            } catch (Exception ex) {
                Logger.getLogger(StrutsDispatcher.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        String file=config.getInitParameter("struts");
        System.out.println(config.getServletContext());
        InputStream input=config.getServletContext().getResourceAsStream(file);
        System.out.println(input);
        ActionFactory.initActions(input);
    }

  

}








分享到:
评论

相关推荐

    讲课宝课堂互动教学系统使用教程

    讲课宝课堂互动系统适用于各类需要互动的场所,如课堂教学互动、大型活动互动等。

    讲课用的小组评比工具

    总结来说,"讲课用的小组评比工具"是一款强大的教学辅助软件,它将评分过程变得简单而高效,为教师提供了更全面、更公平的评价手段,同时也促进了学生的主动学习和团队合作。在信息化教育时代,这样的工具无疑能极大...

    赖世雄中级讲课笔记\赖世雄中级讲课笔记.zip

    《赖世雄中级英语讲课笔记》是一份宝贵的英语学习资源,由知名英语教育专家赖世雄教授精心编纂。这份笔记涵盖了中级英语的学习要点,旨在帮助学习者提升英语能力,尤其是听力、阅读、写作和口语方面的技能。赖世雄...

    课堂管理策略讲课提纲.pptx

    课堂管理策略讲课提纲.pptx

    单片机课件4——课堂讲课课件

    程序中遇到另一个 `ORG` 指令时,新的地址开始计算。这样可以确保程序在内存中的连续性。 2. **等值指令**: `EQU` 指令用于给字符名称赋予一个数值或汇编符号,方便程序的编写、调试和修改。例如,`PA8155 EQU ...

    课堂教学改革模式讲课讲稿.pdf

    "课堂教学改革模式讲课讲稿"探讨了如何打破传统的教学模式,构建适应新时代需求的教育方式。改革的核心理念是以学生为中心,以教育教学理论和规律为基础,遵循新课程理念,旨在优化教学结构,提高教学效率,促进学生...

    单片机5——课堂讲课课件

    单片机5——课堂讲课课件的内容主要围绕MCS-51单片机的中断系统进行讲解,这一章深入探讨了中断的概念、中断源、中断优先级以及MCS-51单片机中断系统的具体实现。 中断是计算机系统中一种重要的机制,它允许计算机...

    单片机6——课堂讲课课件

    单片机讲解,我们学校老师的课件,对单片机感兴趣的同学可以看看!

    如何做好模拟课堂(试讲)讲课.doc

    【如何做好模拟课堂讲课】 1. **充分准备**:了解应聘学科,把握教材重点,增强自信心,避免紧张导致表达不清或语速过快。 2. **教案撰写**:根据试讲时间限制,选择合适的内容,可以是某个知识点的深入讲解,而...

    struts2详解

    全面讲诉struts2的文档,是讲课或是学的好资料啊。

    考研写作讲义-与老师面授课堂上讲课所述讲义完全一致

    一篇优秀的考研英语作文通常包括三个主要部分:Introduction(引言)、Body(主体)和Conclusion(结论)。 1. Introduction(引言) - General description(整体描述):简要介绍文章主题。 - Details(细节)...

    单片机8——课堂讲课课件

    单片机应用系统的设计与开发是一个综合性的工程过程,涉及到硬件和软件的紧密配合。在开发过程中,首先要进行方案论证,了解用户需求,确定设计规模和总体框架,评估技术难度,并进行调研,确定初步设计方案。在此...

    tcp协议简单讲课

    在这个“tcp协议简单讲课”中,我们将会深入探讨TCP协议的基本概念、工作原理以及它在实际网络通信中的应用。 TCP是一种面向连接的、可靠的、基于字节流的传输层通信协议。它在两台计算机之间建立连接后,才能进行...

    课堂截屏工具(好用简单)

    例如,在教授编程、设计或者科学实验等需要展示步骤的课程时,教师可以连续截取每一个关键步骤,形成完整的操作流程图,方便学生课后复习或查阅。同时,实时截屏功能也使得在线教学更加生动,让学生如同亲临现场般地...

    Cocos2D-X开发学习笔记-渲染框架之布景层类的使用示例

    Cocos2D-X是一款流行的开源游戏开发框架,尤其在2D游戏领域中广泛应用。它基于C++,同时提供了Lua和JavaScript的绑定,让开发者可以选择不同的编程语言进行游戏开发。本篇学习笔记主要聚焦于Cocos2D-X的渲染框架,...

    单片机10——课堂讲课课件

    它内置2KB的可编程闪速存储器,能够进行上千次的擦写操作,并且数据能够保留长达10年。其工作电压范围为2.7V到6V,适应性强,能够在各种电源环境下工作。此外,AT89C2051支持全静态工作模式,频率可达24MHz,提供128...

    单片机3——课堂讲课课件

    2. **直接寻址**:指令直接给出操作数的地址,能访问内部数据存储器的低128个字节、特殊功能寄存器和位地址空间。 3. **寄存器寻址**:操作数存储在工作寄存器R0-R7、累加器A、寄存器B、DPTR或位累加器C中。 4. **...

    小黑课堂独家课程资料.rar

    【小黑课堂独家课程资料.rar】是一份专为学习计算机二级考试准备的资源包,它涵盖了计算机基础知识、操作系统、网络技术、数据库管理、程序设计语言等多个核心领域。这份压缩包旨在帮助学员系统地掌握和复习计算机二...

    如何上好政治试题评讲课 (2).docx

    这一过程涉及教师对试卷的批改、统计分析、课堂讲解、个别辅导以及自我反思等多个层面。 首先,认真批改试卷是上好政治试题评讲课的基础。教师需仔细查看每一份试卷,了解学生在哪些问题上表现出色,哪些地方存在...

    单片机7——课堂讲课课件

    单片机系统扩展与接口技术是单片机应用中至关重要的一环,它涉及到单片机如何与外部设备进行有效的通信和数据交换。本章节主要介绍了单片机在扩展外部总线、外部存储器以及输入/输出接口等方面的技术。 首先,外部...

Global site tag (gtag.js) - Google Analytics