MVC design pattern of Java Web

MVC design pattern of Java Web

When writing a Java Web project, you will find that with the increase of code in a medium-sized or large-scale project, you will find that the code can be written in the src directory or

Write in the WebContent directory. Many packages can be built under src and many folders can be built under WebContent.

So the question arises: in which directory and folder is a new class written?

At this point, the solution is: a pattern is needed to standardize which class should be written where.

1.mvc

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5uc20k91-1601194717875) (C: \ users \ ASUS \ appdata \ roaming \ typora user images \ image-20200925153509584. PNG)]

In the Web MVC mode, the model cannot actively push data to the view. If the user wants to update the view, he needs to send another request (i.e. request response module)

Type).

M(Model) model: the core function of the application, which manages the data and values (beans, Dao) used in this module;

V(View): the view provides the display of the model, manages how the model is displayed to the user, and it is the appearance of the application; (jsp/html)

C(Controller) controller: it responds to user input and manages the interaction between user and view. It is the hub connecting model and view.

(servlet/service)

2. Three tier architecture

The three-tier architecture in the general sense is to divide the whole business application into: presentation layer (UI), business logic layer (BLL) and data access layer

(DAL). The purpose of distinguishing levels is the idea of "high cohesion and low coupling".

1. Presentation layer (UI): Generally speaking, it is the interface presented to the user, that is, what the user sees when using a system. jsp/html

2. Business logic layer (BLL): the operation for specific problems can also be said to be the operation on the data layer and the processing of data business logic.

servlet,service

3. Data access layer (DAL): the transactions done by this layer directly operate the database for data addition, deletion, modification, update, search, etc. dao

The representative works of the implementation of the presentation layer are struts and spring MVC framework,

The representative work of the business layer implementation is Spring,

The representative works of persistence layer implementation are hibernate and mybatis.

Layer is equivalent to a black box. We don't need to know how to implement it internally, we just need to know how to call it. Each floor is only adjacent to the upper and lower two floors

Dealing with layers. When a layer changes due to technological changes, as long as the interface remains unchanged, other layers do not need to make any changes. Increased flexibility after Tiering,

It is also convenient for team development.

3. Differences and relations between three-tier architecture and MVC

[external link image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-yrrkb36f-1601194717878) (C: \ users \ ASUS \ appdata \ roaming \ typora \ typora user images \ image-20200925154009520. PNG)]

Design demo

1. Package structure

SRC directory

Create com java. Web package. The code of the corresponding servlet is stored below.

Create com java. Service package. The code of business logic is stored below. The interface layer between servlet and dao. Servlet calls service and service calls dao.

Create com java. Dao package, which contains the operation information of the database.

Create com java. Bean package, with entity classes below.

Create com java. Util package, put the tool class below.

2. Demo model, model layer, bean package and dao package

Query all the information of students in the database student table

1. Create the above package

2. Deployment

2.1. Add request instruction on the page

<h1><a href="/getallstudent">student</a></h1>

2.2. Create a new class in the web package to store servlet s

1. Create xxServlet class

2. Inheritance and HttpServlet

3. Rewrite the service method

package com.java.web;

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 java.io.IOException;

@WebServlet(value = "/getallstudent")//Receive page instructions through annotations
class StudentServlet extends HttpServlet {//Inherit HttpServlet. If you can't find it here, you need to import the jar package under the lib directory of tomcat
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//Override service method
        
        //1. Accept parameters
        //2. Call service method
        //3. Jump to page
    }
}

3. Create entity class in bean package

Entity class, also known as javabean

1. Try to make the class name equal to the table name and the column name equal to the attribute name

2. Construction method

package com.java.bean;
//The class name must be equal to indicates that the list must be equal to the attribute name
public class Student {
    private String sname;
    private String sid;
        //.
        //.
        //.
        //.
        //.
        //Generate get,set, all parameter and no parameter methods
}

4.dao package

4.1. Create an interface, StudentDao. Define how to operate the database

ackage com.java.dao;

import com.java.bean.Student;

import java.util.List;

public interface StudentDao {
    public List<Student> getall();

}

4.2. Create impl. Under dao package StudentDaoImpl

Implement dao interface and connect to database

1. First, create the lib package under the WEB-INF folder and put the Druid jar package in it

2. Then place the Druid's attribute file in src

url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10
minIdle=5
maxWait=3000

3. The Druid's tool classes are placed in the util directory, which contains methods to obtain connection and close resources

4. The studentdaoimpl implementation class implements the methods in dao and connects to the database

package com.java.dao.impl;

import com.java.bean.Student;
import com.java.dao.StudentDao;
import com.java.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl extends DruidUtil implements StudentDao {

    @Override
    public List<Login> getall() {
        List list = new ArrayList();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = getConnection();
            String sql = "select * from Student";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Student student = new Student();
                login.setsname(resultSet.getString("sname"));
                login.setsid(resultSet.getString("sid"));
                list.add(studetn);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close(connection,preparedStatement,resultSet);
        }

        return null;
    }
}

5.Service

1. Copy Dao to Service and rename it StudentService

2. Create an implementation class, impl Studentserviceimpl. The interface is StudentService

public class StudentServiceImpl implements StudentService {
    private StudentDao dao = new StudentDaoImpl();
    @Override
    public List<Student> getall() {
        return dao.getall();
    }
}

6.Servlet

@WebServlet(value = "/Student")
class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Accept parameters
        //2. Call service method
        StudentService studentService = new StudentServiceImpl();
        List<Studnet> students = studentService.getall();
        //3. Jump to page
		req.setAttribute("lgoins",logins);
        req.getRequestDispatcher("show.jsp").forward(req,resp);
    }
}

Call service from servlet, dao from service and database from dao. The data is saved in the entity class

);
List students = studentService.getall();
//3. Jump page
req.setAttribute("lgoins",logins);
req.getRequestDispatcher("show.jsp").forward(req,resp);
}
}

servlet Inside transfer service,service Inside transfer dao,dao Call the database inside. The data is saved in the entity class

### Import tag library, show, TL 7

Tags: Java

Posted by guayaquil on Sat, 14 May 2022 14:36:12 +0300