MVC design pattern examples

view layer: JSP and display data transmission:


17077277-797d5b645bec91c9.png

Controller layer:

servlet: multiple requests to call a 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 {

// get 1 ServletPath: /edit.do or add.do

        String servletPath = request.getServletPath();

        // 2. removing / and .do, obtain such string edit and add similar

        try {

String methodName = servletPath.substring(5);

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

            System.out.println(methodName);

            Method // 3. MethodName acquired by reflection corresponding

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

            // 4. The method of using reflection to invoke the corresponding

            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);

    }

}

Data layer:

JDBC tool uses DBUtils

Database connection pool: c3p0

By DAO design model, reflective, generic, universal configuration database background operation code:

Greatly increasing the reusability of code database back-end operations


17077277-8c7c2385b0569d0f.png


17077277-87a635e1d2413926.png

Guess you like

Origin blog.csdn.net/weixin_34387284/article/details/91031084