码迷,mamicode.com
首页 > 编程语言 > 详细

java实现简单的MVC框架

时间:2018-10-18 13:16:36      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:this   stream   tac   pat   pack   system   not   模式   ati   

一、mvc的模式如下图所示

技术分享图片

二、基于路径访问的控制器

控制器BaseServlet类如下

package com.wangyang.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangyang.model.ShopSc;
import com.wangyang.util.PropertiesUtil;

@WebServlet("/")
public class BaseServlet extends HttpServlet{
    private Map<String, String> map = new HashMap<String, String>();
    private static final long serialVersionUID = 1L;
    @Override
    public void init(ServletConfig config) throws ServletException {
        Properties prop = PropertiesUtil.getMvcProp();
        for(String key : prop.stringPropertyNames()){
            map.put(key, prop.getProperty(key));
        }
        System.out.println(map);
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        path(req, resp);
    }/**
     * 基于路径的映射
     */
    public void path(HttpServletRequest req, HttpServletResponse resp){
        String method = req.getRequestURI().replace(req.getServletContext().getContextPath()+"/", "");
        try {
            String[] str = method.split("/");
            String className;
            String methodName;
            if(str.length<=1){
                className=str[0];
                methodName="execute";
            }else{
                className = str[0];
                methodName = str[1];
            }
            
            System.out.println(className+"--"+methodName);
            Class<?> clz;
            try {
                clz = Class.forName(map.get(className));
            } catch (NullPointerException e1) {
                error("没有找到处理的类!!", req, resp);
                return;
            }
            Method m;
            try {
                m = clz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            } catch (NoSuchMethodException e) {
                error("该类没有要执行的方法!!", req, resp);
                return;
            }
            String path = (String)m.invoke(clz.newInstance(), req,resp);
            req.getRequestDispatcher("/WEB-INF/"+path).forward(req, resp);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void error(String msg,HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
        req.setAttribute("error",msg);
        req.getRequestDispatcher("/WEB-INF/error.jsp").forward(req, resp);
    }
}

配置文件PropertiesUtil的编写

package com.wangyang.util;

import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil {private static Properties mvcProp;public static Properties getMvcProp(){
        try {
            if(mvcProp==null){
                mvcProp = new Properties();
                mvcProp.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("mvc.properties"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mvcProp;
    }
}
mvc.properties的编写

user=com.wangyang.web.UserServlet
address=com.wangyang.web.AddressServlet

 

package com.wangyang.web;

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

public class AddressServlet {
    public String list(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("address", "list");
        return "address.jsp";
    }
    public String execute(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("address", "execute addredss");
        return "address.jsp";
    }
}
package com.wangyang.web;

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

public class AddressServlet {
    public String list(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("address", "list");
        return "address.jsp";
    }
    public String execute(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("address", "execute addredss");
        return "address.jsp";
    }
}

 

结果如下图

技术分享图片

三、基于参数访问的控制器

 

package com.wangyang.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangyang.model.ShopSc;

public class BaseServlet extends HttpServlet{
    
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        method2(req, resp);
    }
    
    public void method2(HttpServletRequest req,HttpServletResponse resp){
        String methodName = req.getParameter("method");
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            String path = (String)method.invoke(this, req,resp);
            req.getRequestDispatcher("WEB-INF/"+path).forward(req, resp);;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
}

 

package com.wangyang.web;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangyang.model.ShopSc;

@WebServlet("/user")
public class UserServlet extends BaseServlet{
    
    
    static final long serialVersionUID = 1L;
    //@ShopSc("user/index.jsp")
    public String add(HttpServletRequest req, HttpServletResponse resp){
        req.setAttribute("name", "wangyang");
        return "user/index.jsp";
    }
    
}

 

技术分享图片

无论使那种控制器,都是获取url的参数,之后利用反射去调用相应的方法

 

java实现简单的MVC框架

标签:this   stream   tac   pat   pack   system   not   模式   ati   

原文地址:https://www.cnblogs.com/wangyang1749/p/9805385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!