java实现简单的MVC框架

一、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的参数,之后利用反射去调用相应的方法

猜你喜欢

转载自www.cnblogs.com/wangyang1749/p/9805385.html