Servlet3.0实现的简单mvc框架

jar包准备:servlet-api-3.0.jar
项目结构如下:
这里写图片描述

注解Mapping ,用于映射url地址

/*
 * 文件名:Action.java
 * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述: Action.java
 * 修改人:peiyu
 * 修改时间:2016年7月29日
 * 修改内容:新增
 */
package com.servlet3.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
    String value();
}

ActionModel,用于封装Action信息

/*
 * 文件名:ActionModel.java
 * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述: ActionModel.java
 * 修改人:peiyu
 * 修改时间:2016年8月1日
 * 修改内容:新增
 */
package com.servlet3.util;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author     peiyu
 */
public class ActionModel implements Serializable{

    /**
     * 添加字段注释.
     */
    private static final long serialVersionUID = 1L;

    private String className;
    private Method method;
    private Object action;
    /**
     * 设置className.
     * @return 返回className
     */
    public String getClassName() {
        return className;
    }
    /**
     * 获取className.
     * @param className 要设置的className
     */
    public void setClassName(String className) {
        this.className = className;
    }
    /**
     * 设置method.
     * @return 返回method
     */
    public Method getMethod() {
        return method;
    }
    /**
     * 获取method.
     * @param method 要设置的method
     */
    public void setMethod(Method method) {
        this.method = method;
    }
    /**
     * 设置action.
     * @return 返回action
     */
    public Object getAction() {
        return action;
    }
    /**
     * 获取action.
     * @param action 要设置的action
     */
    public void setAction(Object action) {
        this.action = action;
    }
}

MyFilter过滤器,初始化时创建扫描指定包下的所有类的注解,解析URL,创建Bean

/*
 * 文件名:MyFilter.java
 * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述: MyFilter.java
 * 修改人:peiyu
 * 修改时间:2016年7月29日
 * 修改内容:新增
 */
package com.servlet3.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.servlet3.annotation.Mapping;
import com.servlet3.exception.URLException;
import com.servlet3.util.ActionModel;
import com.servlet3.util.CommentedProperties;

/**
 * 
 * @author peiyu
 */
@WebFilter(filterName = "MyFilter", urlPatterns = {"/*"})
public class MyFilter implements Filter {
    @Override
    public void destroy() {
        System.out.println("-----------------------destroy-----------------------");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String uri = httpServletRequest.getRequestURI();
        //访问的逻辑地址/myServlet3
        String url = uri.substring(uri.indexOf("/", 1));
        httpServletRequest.getRequestURL();
        System.out.println("-----------------------doFilter-----------------------");
        request.setAttribute("url", url);
        request.getRequestDispatcher("/myServlet3").forward(request,response);

    }
    /**
     *1. 获取配置文件中配置的需扫描的包名
     *2. 根据包名扫描注解,获取URL,创建Bean实例
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
      //获取配置文件中的包路径
        CommentedProperties properties = new CommentedProperties();
        //   /D:/software/apache-tomcat-7.0.59/webapps/Servlet3.0/WEB-INF/classes/scan-package.properties
        String classPath = MyFilter.class.getClassLoader().getResource("").getPath();
        String path = classPath + "scan-package.properties";
        System.out.println("####1加载配置文件:" + path);
        try {
            path = URLDecoder.decode(path, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        System.out.println("####2加载配置文件:" + path);
        try {
            properties.load(new FileInputStream(path), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取到包路径
        String scanPackage = properties.getProperty("scan-package").replace(".", "/");
        /*************************** 扫描包下的所有文件 ***************************************/
        //获取到class文件路径
        path = classPath + scanPackage;
        Map<String, ActionModel> urls = new HashMap<>();
        File file = new File(path);
        //获取Action,url信息
        getFileUrls(file, urls);
        //将Action,url信息放到ServletContext
        config.getServletContext().setAttribute("urls", urls);
    }
    /**
     * 获取URL.
     */
    private void getFileUrls(File file, Map<String, ActionModel> urls) {
        if (file.isDirectory()) { //如果是文件夹,获取文件夹下的文件
            File[] files = file.listFiles();
            for (File temp : files) {
                if (temp.isDirectory()) {
                    getFileUrls(temp, urls);
                } else {
                    getFileUrl(temp, urls);
                }
            }
        } else { //如果是文件
            getFileUrl(file, urls);
        }
    }

    /**
     * 获取URL,创建Action bean.
     */
    @SuppressWarnings("rawtypes")
    private void getFileUrl(File temp, Map<String, ActionModel> urls) {
        String path;
        path = temp.getPath();
        String className = path.substring(path.indexOf("com"), path.lastIndexOf(".")).replace("\\", ".");
        try {
            Class clazz = Class.forName(className);
            //获取类注解
            String startUrl = "";
            //Annotation[] annotations = clazz.getAnnotations();
            //for (Annotation annotation : annotations) {
            //   if (annotation instanceof Mapping) { //判断是mapping
            //       startUrl = ((Mapping) annotation).value();
            //    }
            //}
            if (clazz.isAnnotationPresent(Mapping.class)) {
                startUrl = ((Mapping)clazz.getAnnotation(Mapping.class)).value();
            }
            //获取方法上注解
            Method[] methods = clazz.getMethods();
            Object action=clazz.newInstance();
            for (Method method : methods) {
                if (method.isAnnotationPresent(Mapping.class)) {
                    ActionModel actionModel = new ActionModel();
                    actionModel.setClassName(className);
                    actionModel.setMethod(method);
                    actionModel.setAction(action);
                    Mapping annotation=method.getAnnotation(Mapping.class);
                    String key = startUrl + ((Mapping) annotation).value();
                    if (urls.containsKey(key)) {
                        throw new URLException("已存在URL:" + key);
                    } else {
                        urls.put(key, actionModel);
                    }
                }
                //annotations = method.getAnnotations();
                //for (Annotation annotation : annotations) {
                //    if (annotation instanceof Mapping) { //判断是mapping
                //        ActionModel actionModel=new ActionModel();
                //        actionModel.setClassName(className);
                //        actionModel.setMethod(method);
                //        actionModel.setAction(action);
                //        String key = startUrl + ((Mapping) annotation).value();
                //        if (urls.containsKey(key)) {
                //            throw new URLException("已存在URL:"+key);
                //        }else {
                //            urls.put(key, actionModel);
                //        }
                //    }
                //}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

scan-package.properties配置需要扫描的包

scan-package=com.servlet3.controller

默认访问的Servlet,通过该Servlet找到指定的URL地址

/*
 * 文件名:MyServlet3.java
 * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述: MyServlet3.java
 * 修改人:peiyu
 * 修改时间:2016年7月29日
 * 修改内容:新增
 */
package com.servlet3.controller;

import java.io.IOException;
import java.util.Map;

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

import com.servlet3.util.ActionModel;

/**
 * name:当前Servlet 的名称
 * urlPatterns:请求的url
 * loadOnStartup:tomcat启动时就初始化该servlet
 * initParams:初始化参数
 * name:参数名
 * value:参数值
 * 
 * @author peiyu
 */
@WebServlet(name = "MyServlet3", 
urlPatterns = {"/myServlet3"}, 
loadOnStartup = 1, 
initParams = {@WebInitParam(name = "name", value = "java"), 
                     @WebInitParam(name = "age", value = "1")})
public class MyServlet3 extends HttpServlet {
    /**
     * 添加字段注释.
     */
    private static final long serialVersionUID = 1L;
    @SuppressWarnings({"unchecked"})
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url=(String) req.getAttribute("url");
        Map<String, ActionModel> urls =(Map<String, ActionModel>) req.getServletContext().getAttribute("urls");
        ActionModel actionModel=urls.get(url);
        if (actionModel!=null) {
            try {
                Object res=actionModel.getMethod().invoke(actionModel.getAction(), req,resp);
                //根据返回的结果类型,返回值进行处理
                if (res instanceof String) {
                    if (((String) res).startsWith("redirect:")) {
                        //......
                    }else if (((String) res).startsWith("forward:")) {
                        //......
                    }
                }else{
                    //......
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

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

测试的UserAction

/*
 * 文件名:UserAction.java
 * 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述: UserAction.java
 * 修改人:peiyu
 * 修改时间:2016年7月29日
 * 修改内容:新增
 */
package com.servlet3.controller;

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

import com.servlet3.annotation.Mapping;

/**
 * @author     peiyu
 */
@Mapping(value="/myServlet3")
public class UserAction {

    @Mapping(value="/login")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("--------login-------------");
        return "redirect:register";
    }
    //register
    @Mapping(value="/register")
    public String register(HttpServletRequest req, HttpServletResponse resp){

        System.out.println("--------register-------------");
        return "redirect:login";
    }
}

最后,启动服务器,访问http://localhost:8072/Servlet3.0/myServlet3/login?name=java&age=1就会找到UserAction的login方法。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值