MVC设计模式实例

view层:jsp展示和传输数据:


17077277-797d5b645bec91c9.png

控制器层:

servlet:多个请求调用一个servlet:


17077277-d567c252070b0b3e.png

@WebServlet(name ="CustomerServlet",urlPatterns ="*.do")

public class CustomerServletextends HttpServlet {

//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        String method = request.getParameter("method");

//        switch (method){

//            case "add":add(request,response);break;

//            case "query":query(request,response);break;

//            case "delete":delete(request,response);break;

//        }

//    }

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

//1.获取ServletPath:/edit.do或add.do

        String servletPath = request.getServletPath();

        //2.去除/和.do,得到类似于edit和add这样的字符串

        try {

String methodName = servletPath.substring(5);

            methodName = methodName.substring(0,methodName.length()-3);

            System.out.println(methodName);

            //3.利用反射获取methodName对应的方法

            Method method = getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);

            //4.利用反射调用对应的方法

            method.invoke(this,request,response);

        }

catch (Exception e) {

request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request,response);

      //            e.printStackTrace();

        }

}

private void add(HttpServletRequest request,HttpServletResponse response)throws ServletException{

System.out.println("add");

    }

private void query(HttpServletRequest request,HttpServletResponse response)throws ServletException{

System.out.println("query");

    }

private void delete(HttpServletRequest request,HttpServletResponse response)throws ServletException{

System.out.println("delete");

    }

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

doPost(request,response);

    }

}

数据层:

JDBC工具采用DBUtils

数据库连接池为:c3p0

通过DAO设计模型,反射,泛型,构成后台操作数据库代码的通用性:

大大增加后台操作数据库代码的重用性


17077277-8c7c2385b0569d0f.png


17077277-87a635e1d2413926.png

猜你喜欢

转载自blog.csdn.net/weixin_34387284/article/details/91031084