• 自定义MVC实现登录案例


    MVC框架: MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

    我们今天自己定义的MVC框架是简单模仿struts2的

    然后我们会用到两个常用的技能点,一个是使用dom4j解析xml文件,还有一个是java反射机制。

    案例架构:

    1.导入依赖jar包:

     1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     3     <parent>
     4         <artifactId>01MyBatis</artifactId>
     5         <groupId>cn.happy</groupId>
     6         <version>1.0-SNAPSHOT</version>
     7     </parent>
     8     <modelVersion>4.0.0</modelVersion>
     9     <artifactId>12CustomMVC</artifactId>
    10     <packaging>war</packaging>
    11     <name>12CustomMVC Maven Webapp</name>
    12     <url>http://maven.apache.org</url>
    13     <dependencies>
    14         <dependency>
    15             <groupId>junit</groupId>
    16             <artifactId>junit</artifactId>
    17             <version>4.3</version>
    18             <scope>test</scope>
    19         </dependency>
    20 
    21         <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
    22         <dependency>
    23             <groupId>dom4j</groupId>
    24             <artifactId>dom4j</artifactId>
    25             <version>1.6.1</version>
    26         </dependency>
    27 
    28         <!--ServletAPI-->
    29         <dependency>
    30             <groupId>javaee</groupId>
    31             <artifactId>javaee-api</artifactId>
    32             <version>5</version>
    33         </dependency>
    34     </dependencies>
    35     <build>
    36         <resources>
    37             <resource>
    38                 <directory>src/main/java</directory>
    39                 <includes>
    40                     <include>**/*.*</include>
    41                 </includes>
    42             </resource>
    43         </resources>
    44     </build>
    45 </project>

    2..定义自己的dtd约束文件和配置信息:

     1 <?xml version='1.0' encoding='UTF-8'?>
     2 <!DOCTYPE myframe[
     3         <!ELEMENT myframe (actions)>
     4         <!ELEMENT actions (action*)>
     5         <!ELEMENT action (result*)>
     6         <!ATTLIST action
     7                 name CDATA #REQUIRED
     8                 class CDATA #REQUIRED>
     9         <!ELEMENT result (#PCDATA)>
    10         <!ATTLIST result
    11                 name CDATA #IMPLIED
    12                 redirect (true|false) "false">
    13         ]>
    14 <myframe>
    15     <actions>
    16         <action name="login" class="cn.curry.action.LoginAction">
    17             <result name="success">/success.jsp</result>
    18             <result name="login">login.jsp</result>
    19         </action>
    20     </actions>
    21 </myframe>

    3.分层搭建

    Action:

    Action  自己定义的结果集和执行方法 :

     1 package cn.curry.action;
     2 
     3 import javax.servlet.http.HttpServletRequest;
     4 import javax.servlet.http.HttpServletResponse;
     5 
     6 /**
     7  * Created by Administrator on 2018/3/4.
     8  */
     9 public interface Action {
    10     //定义字符串常量
    11     public static final String SUCCESS="success";
    12     public static final String NONE="none";
    13     public static final String ERROR="error";
    14     public static final String INPUT="input";
    15     public static final String LOGIN="login";
    16     //准备一个方法,用于获取数据
    17     public String execute(HttpServletRequest request, HttpServletResponse response)throws Exception;
    18 }

     定义一个ActionMapping用来存放Action节点

     1 package cn.curry.action;
     2 
     3 import java.util.HashMap;
     4 import java.util.Map;
     5 
     6 /**
     7  * Created by Administrator on 2018/3/4.
     8  */
     9 public class ActionMapping {
    10     private String name;
    11     private String className;
    12     private Map<String,String> map=new HashMap<String, String>();
    13 
    14     public String getName() {
    15         return name;
    16     }
    17 
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21 
    22     public String getClassName() {
    23         return className;
    24     }
    25 
    26     public void setClassName(String className) {
    27         this.className = className;
    28     }
    29 
    30     public String getValue(String key) {
    31         return map.get(key);
    32     }
    33 
    34     public void addToMap(String key,String value) {
    35         map.put(key,value);
    36     }
    37 }

    定义ActionManager  通过类名用反射机制获取对象

     1 package cn.curry.action;
     2 
     3 /**
     4  * Created by Administrator on 2018/3/4.
     5  */
     6 public class ActionManager {
     7     public static Action getActionClass(String className) throws Exception{
     8         Class clazz=null;
     9         Action action=null;
    10         clazz=Thread.currentThread().getContextClassLoader().loadClass(className);
    11         if (clazz==null){
    12             clazz=Class.forName(className);
    13         }
    14         if (action==null){
    15             action=(Action) clazz.newInstance();
    16         }
    17         return action;
    18     }
    19 }

    ActionMappingManager  通过dom4j读取xml

     1 package cn.curry.action;
     2 
     3 import org.dom4j.Document;
     4 import org.dom4j.Element;
     5 import org.dom4j.io.SAXReader;
     6 
     7 import java.io.InputStream;
     8 import java.util.HashMap;
     9 import java.util.Iterator;
    10 import java.util.Map;
    11 
    12 /**
    13  * Created by Administrator on 2018/3/4.
    14  */
    15 public class ActionMappingManager {
    16     private Map<String,ActionMapping> map=new HashMap<String, ActionMapping>();
    17 
    18     public  ActionMapping getValue(String key) {
    19         return map.get(key);
    20     }
    21 
    22     public void addToMaps(String key,ActionMapping value) {
    23         map.put(key,value);
    24     }
    25 
    26     public ActionMappingManager(String [] files)throws Exception{
    27         for (String item:files){
    28             init(item);
    29         }
    30     }
    31     public void init(String path)throws Exception{
    32         InputStream is=this.getClass().getResourceAsStream("/"+path);
    33         Document doc=new SAXReader().read(is);
    34         Element root=doc.getRootElement();
    35         Element actions=(Element)root.elements("actions").iterator().next();
    36         for (Iterator<Element> action = actions.elementIterator("action"); action.hasNext();){
    37             Element actionnext=action.next();
    38             ActionMapping am=new ActionMapping();
    39             am.setName(actionnext.attributeValue("name"));
    40             am.setClassName(actionnext.attributeValue("class"));
    41             for (Iterator<Element> result=actionnext.elementIterator("result");result.hasNext();){
    42                 Element resultnext=result.next();
    43                 String name=resultnext.attributeValue("name");
    44                 String value=resultnext.getText();
    45                 if (name==null||"".equals(name)){
    46                     name="success";
    47                 }
    48                 am.addToMap(name,value);
    49             }
    50             map.put(am.getName(),am);
    51         }
    52     }
    53 }

    接下来我们定义一个Servlet来获取请求LoginServlet 主通过获取的请求找到Framework.xml

     1 package cn.curry.servlet;
     2 
     3 import cn.curry.action.Action;
     4 import cn.curry.action.ActionManager;
     5 import cn.curry.action.ActionMapping;
     6 import cn.curry.action.ActionMappingManager;
     7 
     8 import javax.servlet.ServletConfig;
     9 import javax.servlet.ServletException;
    10 import javax.servlet.http.HttpServlet;
    11 import javax.servlet.http.HttpServletRequest;
    12 import javax.servlet.http.HttpServletResponse;
    13 import java.io.IOException;
    14 
    15 /**
    16  * Created by Administrator on 2018/3/4.
    17  */
    18 public class LoginServlet extends HttpServlet {
    19     private ActionMappingManager manager=null;
    20     private String getClassName(HttpServletRequest request){
    21         String uri=request.getRequestURI();
    22         System.out.println(uri+"        uri");
    23         String context=request.getContextPath();
    24         System.out.println(context+"             context");
    25         String result=uri.substring(context.length());
    26         System.out.println(result+"              result");
    27         return result.substring(1,result.lastIndexOf("."));
    28     }
    29 
    30 
    31     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    32         String key=getClassName(request);
    33         System.out.println(key+"           key");
    34         try {
    35             ActionMapping actionMapping=manager.getValue(key);
    36             System.out.println(actionMapping.getClassName()+"            classname");
    37             Action action= ActionManager.getActionClass(actionMapping.getClassName());
    38             String result=action.execute(request,response);
    39             System.out.println(result+"                   result");
    40             String path=actionMapping.getValue(result);
    41             System.out.println(path+"                path");
    42             request.getRequestDispatcher(path).forward(request,response);
    43         } catch (Exception e) {
    44             e.printStackTrace();
    45         }
    46     }
    47 
    48     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    49         doPost(request,response);
    50     }
    51 
    52     public void init(ServletConfig config) throws ServletException {
    53         String fileName=config.getInitParameter("config");
    54         String file[]=null;
    55         if(fileName==null){
    56             file=new String[]{"Framework.xml"};
    57         }else {
    58             fileName.split(",");
    59         }
    60         try {
    61             manager=new ActionMappingManager(file);
    62         } catch (Exception e) {
    63             e.printStackTrace();
    64         }
    65     }
    66 }

    配置web.xml文件

     1 <!DOCTYPE web-app PUBLIC
     2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
     4 
     5 <web-app>
     6   <display-name>Archetype Created Web Application</display-name>
     7     <servlet>
     8         <servlet-name>LoginServlet</servlet-name>
     9         <servlet-class>cn.curry.servlet.LoginServlet</servlet-class>
    10     </servlet>
    11     <servlet-mapping>
    12         <servlet-name>LoginServlet</servlet-name>
    13         <url-pattern>*.action</url-pattern>
    14     </servlet-mapping>
    15 </web-app>

    jsp页面

    login.jsp

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>登录</title>
     5 </head>
     6 <body>
     7 <form action="login.action" method="post">
     8     用户名:<input name="name"><br>
     9     密码:<input name="pwd"/><br/>
    10     <input type="submit" value="登陆"/>
    11 </form>
    12 </body>
    13 </html>

    success.jsp

    <%--
      Created by IntelliJ IDEA.
      User: Administrator
      Date: 2018/3/4
      Time: 19:43
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>登录</title>
    </head>
    <body>
    <h1>success!!!</h1>
    </body>
    </html>

    执行结果;

  • 相关阅读:
    JS事件
    我刚知道的WAP app中meta的属性(转载)
    监控Tomcat解决方案(监控应用服务器系列文章分享)
    Java实现注册邮箱激活验证
    使用iScroll时,input等不能输入内容的解决方法(share)
    iScroll.js 用法参考 (share)
    Myeclipse常用快捷键
    ajax+json+Struts2实现list传递实例讲解
    JSTL的c:forEach标签(${status.index})
    JAVA导出pdf实例
  • 原文地址:https://www.cnblogs.com/liutao1122/p/8505889.html
Copyright © 2020-2023  润新知