自定义MVC

学习MVC的技能点:

MVC设计模式——XML文件的编写(DTD的基本定义格式,使用DTD规范的编写)——Dom4J解析XML文档——反射机制

DTD:

<?xml version="1.0"?>
<!DOCTYPE myframe[
        <!ELEMENT myframe (actions)>
        <!ELEMENT actions (action*)>
        <!ELEMENT action (result*)>
        <!ATTLIST action
                name CDATA #REQUIRED
                class CDATA #REQUIRED>
        <!ELEMENT result (#PCDATA)>
        <!ATTLIST result
                name CDATA #IMPLIED
                redirect (true|false) "false">
]>
<myframe>
    <actions>
        <action name="login" class="cn.action.LoginAction">
            <result name="success">/success.jsp</result>
            <result name="login">/login.jsp</result>
        </action>
    </actions>
</myframe>

Action 定义Action 的接口

public interface Action {
    //自定义Action接口
    public static  final  String SUCCESS="success";
    public static  final  String LOGIN="login";
    public String excute(HttpServletRequest request, HttpServletResponse response)throws Exception;
}

ActionMapping 把解析出来的xml属性存放在ActionMapping这个类中

public class ActionMapping {
    //xml的实体类
    private String name;
    private String className;
    private Map<String,String> map=new HashMap<String, String>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getValue(String key) {
        return map.get(key);
    }

    public void addMap(String key, String value) {
        map.put(key, value);
    }
}

ActionMapping是ActionManager的管理和解析

public class ActionMappingManager {
    //ActionMappingManage是ActionManager的管理类
    private Map<String,ActionMapping> maps=new HashMap<String, ActionMapping>();

    public  ActionMapping getValue(String key) {
        return maps.get(key);
    }

    public void addMaps(String key, ActionMapping value) {
        maps.put(key, value);
    }

    public ActionMappingManager(String[] files)throws Exception{
        for (String path:files){
            init(path);
        }

    }
    public void init(String path) throws Exception {
        //开始解析XML
        InputStream is=this.getClass().getResourceAsStream("/"+path);
        //读取XML文件,获得Document对象
        Document doc=new SAXReader().read(is);
        //获取文档的根元素
        Element root=doc.getRootElement();
        //取得某节点的单个子节点
        Element actions= (Element) root.elements("actions").iterator().next();
        for(Iterator<Element> action = actions.elementIterator("action"); action.hasNext();){
            Element actionnext=action.next();
            //得到ActionMapping中要存放的属性
            ActionMapping am=new ActionMapping();
            am.setName(actionnext.attributeValue("name"));
            am.setClassName(actionnext.attributeValue("class"));
            //遍历某节点的所有属性
            for(Iterator<Element> result=actionnext.elementIterator("result");result.hasNext();){
                Element resultnext=result.next();
                String name=resultnext.attributeValue("name");
                String value=resultnext.getText();
                if(name==null||"".equals(name)){
                    name="success";
                }
                am.addMap(name,value);
            }
            maps.put(am.getName(),am);
        }

    }
}
通过反射获取Action实现类
public class ActionManager {
    //通过反射获取Action实现类
    public static  Action getActionClass(String className)throws Exception{
        Class clazz=null;
        Action action=null;
        clazz=Thread.currentThread().getContextClassLoader().loadClass(className);
        System.out.println(className+"=======================");
        if(clazz==null){
            clazz=Class.forName(className);
        }
        action=(Action)clazz.newInstance();
        return action;
    }
}

Action 的实现

public class LoginAction implements Action {
    //Action实现类
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String name=request.getParameter("name");
        if(name.equals("sa")){
            return  SUCCESS;
        }else {
            return LOGIN;
        }
    }
}

Servlet中

public class LoginServlet extends HttpServlet {
    ActionMappingManager manager=null;

    private String getClassName(HttpServletRequest request){
        //通过Request 系统的类来获取属性值
        String uri=request.getRequestURI(); //cn.action.LoginServlet
        
        String content=request.getContextPath();//8080后的项目名称
        
        String result=uri.substring(content.length()); //截取Login.action
        return result.substring(1,result.lastIndexOf("."));
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //返回Servlet的地址
        String result=getClassName(request);
        //获取到ActionMapping中的属性值
        ActionMapping actionMapping=manager.getValue(result);
        String className=actionMapping.getClassName();
        try {
            System.out.println(className+"=================-----------");
            //反射出login.action里的属性值
            Action action=ActionManager.getActionClass(className);
            String excuteresult= action.excute(request, response);
            String path=actionMapping.getValue(excuteresult);
            request.getRequestDispatcher(path).forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    @Override
    public void init(ServletConfig config) throws ServletException {
        String urls=config.getInitParameter("config");
        String[] files=null;
        if(urls==null){
            files=new String[]{"myframe.xml"};
        }else{
            files=urls.split(",");
        }
        try {
            manager=new ActionMappingManager(files);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>MyFrame</servlet-name>
    <servlet-class>cn.servlet.LoginServlet</servlet-class>
  <load-on-startup>0</load-on-startup>
  </servlet>
<servlet-mapping>
  <servlet-name>MyFrame</servlet-name>
  <url-pattern>*.action</url-pattern>
</servlet-mapping>
  <welcome-file-list>
    <welcome-file>/login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Login.jsp页面

<form action="login.action" method="post">
    <input name="name"> <br>
    <input type="submit">
</form>

 

posted @ 2017-03-16 10:17  时间&amp;煮雨  阅读(162)  评论(0编辑  收藏  举报