A brief review of spring MVC basic learning MVC architecture and the use of servlets


Hello, guys, I'm running snail rz. Of course, you can call me snail Jun. I'm a rookie who has studied Java for more than half a year. At the same time, I also have a great dream, that is, to become an excellent Java Architect one day.

This spring MVC basic learning series is used to record the whole process of my learning the basic knowledge of spring MVC framework (this series is written with reference to the latest spring MVC tutorial of crazy God in station B. because it was sorted out before, but it was not released at that time, there may be errors in some places. I hope you can correct them in time!)

After that, I will try my best to update this series at the speed of two days and one hour. For those who haven't learned the spring MVC framework, please refer to my blog; Of course, the little friends who have studied can also review the basics with me. Finally, I hope I can make progress with you. Come on, programmer!

Today, we come to the first stop of spring MVC basic learning: a brief review of MVC architecture and the use of servlets. No more nonsense. Let's start today's study.

1.Spring MVC learning

1.1 knowledge review

  • SSM: mybatis + Spring + spring MVC (continues the idea of MVC three-tier architecture)

  • JavaSE: study hard, teachers lead, and get started quickly

  • JavaWeb: study hard, teachers lead, and get started quickly

  • SSM framework: study official documents, exercise self-study ability, exercise note taking ability and exercise project ability

  • SpringMVC + Vue - + SpringBoot + SpringCloud + Linux

  • SSM integration: Java Web projects

  • Spring: IOC (inversion of control) and AOP (aspect oriented programming)

  • Spring MVC: implementation process of spring MVC (may be asked in the interview)

  • Spring MVC: SSM framework integration!

1.2 brief review of MVC architecture

1.2.1 what is MVC?

  • MVC is the abbreviation of Model, View and controller. It is a software design specification
  • Code is organized by separating business logic, data and display
  • The main function of MVC is to reduce the two-way coupling between view and business logic
  • MVC is not a design pattern, but an architecture pattern. Of course, different MVCs are different

In short, MVC is a Model (including Pojo, Dao and Service, i.e. data and business) + View (JSP/HTML, display data) + Controller (servlet, get request and return response)

1.2.2 understand each layer of MVC

Model: data model, which provides data to be displayed and contains data and behavior, can be considered as domain model or JavaBean component (including data and behavior). However, it is generally written separately: Data Dao layer (Value Object) and Service layer (behavior Service) That is, the model provides functions such as model data query and model data status update, including data and business

View: it is responsible for displaying the model, which is generally the user interface we see and what customers want to see

Controller: receives the user's request and delegates it to the model for processing (state change). After processing, the returned model data is returned to the view, which is responsible for displaying it, that is, the controller does the work of a dispatcher

  • Dao and Service
  • Servlet: forwarding and redirection

The most typical MVC is the pattern of JSP + Servlet + JavaBean

1.2.3 MVC execution flow chart

1.2.4 knowledge expansion

For example, there is a User entity class: the entity class has 20 fields such as User name, password, birthday, hobby... And the front end needs the data of User name and password fields

  • Front end: data transmission (data transfer of entity class)
  • Pojo: User entity class
  • Vo: UserVo (user view object), for example, only write two fields: user name and password, and then pass them to the front end (equivalent to subdividing the entity class, which is essentially an entity class object)
  • Dto: UserDto (user data transfer object) the data transfer target is often Dao (data access object) to retrieve data from the database

1.2.5 development of model

1. Simply understand the model 1 Era

1-1 basic concepts of model1
  • In the early development of web, model 1 is usually used, and in model 1, it is mainly divided into two layers, view layer and model layer

1-2 advantages and disadvantages of model1

Advantages of Model1: simple architecture, only model layer and view layer, which is more suitable for small project development

Disadvantages of Model1: JSP responsibilities are not single, which is equivalent to serving as both control layer and view layer, which is not easy to maintain

Note: JSP is essentially a Servlet

2. Simply understand the model 2 era

2-1 Model2 basic concepts

Model 2 divides a project into three parts, including view, control and model

Responsibility analysis:

Controller: controller

  • Get form data
  • Call business logic
  • Go to the specified page

Model: Model

  • Business logic
  • Status of saved data

View: View

  • Display page
2-2 difference between model2 and Model1


  • The implementation of model 1 mode is relatively simple and suitable for rapid development of small-scale projects
  • The JSP page in model 1 plays the roles of View and Controller, mixing the control logic and presentation logic, resulting in poor readability of the code


  • Model 2 not only improves the reuse rate of code and the scalability of the project, but also greatly reduces the maintenance cost of the project
  • It increases the scalability and maintenance difficulty of the application, and Model2 eliminates the shortcomings of Model1
2-4 differences between MVC and MVVM

MVC: M: Model (Model layer); V: View (View layer); C: Controller (control layer)

MVVM: M: Model (Model layer); V: View (View layer); VM: ViewModel (View Model layer), that is, two-way data binding

3. Knowledge expansion

Interview FAQs:

Q: is the architecture of your project designed or evolved?


The project architecture is evolving, because no project can design a good architecture at the beginning. The underlying architecture is constantly evolving, including large companies like Ali

  • Alibaba just started using PHP, which is generally used for personal pages and websites, but there will be problems when the concurrency is tens of millions
  • As the number of users increases, they have no choice but to turn to Java
  • Wang Jian proposed going to IOE, that is, not using IBM and Orcale enterprise software services, and then using MySQL database
  • MySQL: MySQL is an open-source, small, pluggable, component-based database. In fact, there is a layer of architecture at the bottom of SQL. After modification, Alibaba has updated Mysql to AliSQL and AliRedis
  • All in one - > microservices

1.3 simple review Servlet

1.3.1 building basic environment

1. Create project and import resource dependency

1-1 create Maven project
  • To create a normal Maven project, you don't need to check anything else

1-2 import resource dependency
  • Import the relevant resource dependencies in the project's pom.xml configuration file
<!-- Import corresponding resource dependencies -->
    <!-- spring-webmvc resources dependence -->
    <!-- servlet-api resources dependence -->
    <!-- jsp-api resources dependence -->
    <!-- jstl resources dependence -->
    <!-- junit Unit test resource dependency -->

1-3 delete src file of parent project

2. Create subprojects and import resource dependencies

2-1 create Module subproject
  • Right click the parent project name, click New, and then select Module

2-2 creating a normal Maven project
  • Like the parent project, the sub module still chooses to create an ordinary Maven project without checking any options, and then names the sub project

2-3 importing resource dependencies
  • Introduce the relevant resource jar package into the pom.xml configuration file of the subproject
    <!--servlet-api resources dependence-->
    <!--jsp-api resources dependence-->

3. Solve the gray problem of java files in src directory

2-1 view the java files in the src file directory
  • Click the main file under the src file directory and find that the java file under the main file is gray

2-2 add project support
  • Right click the project name and select Add Framework Support... To add project support

2-3 check Web Application
  • Enter the [Add Framework Support...] interface, and then check [Web Application] under the Java EE directory

2-4 check the java file under the src file again
  • Check the main file under the src file directory again, and find that the java file under the main file has changed to blue, and then the web folder has been added, and there is a blue dot on the web file

1.3.2 write control layer Servlet and web.xml configuration file

1. Write HelloServlet of control layer

  • Under the java file under the main file in the src directory, create a com.kuang.cotoller package to store the HelloServlet class of the control layer
package com.kuang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloServlet extends HttpServlet {
     * 1.Override doGet method
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         * 1.1 Get front end parameters
        String method =req.getParameter("method");
        // Determine whether the called request is an add method or a delete method
        if(method.equals("add")) {
            // Execute the add method
            req.getSession().setAttribute("msg","Yes add method");
        if(method.equals("delete")) {
            // Execute the delete method
            req.getSession().setAttribute("msg","Yes delete method");
        * 1.2 Call business layer
        * In order to save trouble, the specific business logic is not written
         * 1.3 View transfer or redirection
        // 1.3.1 use forwarding request
        // 1.3.2 or use redirection
//        resp.sendRedirect();
     * 2.Override doPost method
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);

2. Write the web.xml configuration file

  • Find the web.xml configuration file under the WEB-INF file in the web directory, and configure the servlet and mapping
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    <!-- 1.to configure servlet -->
    <!-- 2.to configure servlet-mapping -->
        <!-- request hello The page will then be automatically forwarded to hello of servlet To handle -->
    <!-- 3.to configure session -->
        <!-- Set the timeout, and close the session automatically after 15 minutes -->
    <!-- 4.Configure welcome page -->
         <!-- The default welcome page is set to index.jsp -->

1.3.3 compiling view layer JSP pages

  • Under the WEB-INF file in the web folder, create a jsp folder to store the relevant page files of the view layer

1. Write test.jsp test page

  • The information used to display the invocation method in Servlet.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

2. Write form.jsp form page

  • A form page used to submit data information
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<form action="/hello" method="post">
    <input type="text" name="method"/>
    <input type="submit" value="Submit"/>

1.3.4 configuring TomCat server

1-1 editing configuration information
  • Click the toolbar graphic line at the top left of the IDEA compiler, find the hammer icon, and click Add Configurations. Because I have already configured it, Edit Configurations is displayed here

1-2 add Tomcat server
  • Click the "+" sign in the upper left corner to add a new configuration, find [Tomcat Server] in the options, that is, Tomcat Server, and then select [Local], that is, use the Local Tomcat Server

1-3 configuring Tomcat server information
  • After adding a local Tomcat Server, Configure the relevant information of the Tomcat Server, find [Application server] under [Server], and click [Configure...] later

  • Then configure the information of [Tomcat Home], find the local Tomcat file location, and then the IDEA will automatically identify the Tomcat version information

  • After returning to the [Server] page again, you will find that the HTTP port and JMX port have been automatically matched. The default port number of Tomcat is 8080 under normal circumstances, but the local Tomcat Server port number has been modified by me, so the display is 8888

1-4 setting and publishing project information
  • Under [Deployment], click the "+" sign on the right and select [Artifact...]

  • Then add the published project information, and finally click Apply in the lower right corner to apply this configuration

1.3.5 test results

1. Start Tomcat server

2. Open the default page

  • After starting the Tomcat server, it will automatically jump to the default index.jsp welcome page

3. Call the add method

  • After adding hello?method=add to the original default URL link, i.e http://localhost:8888/springmvc_ 01_ servlet_ war_ Expanded / hello?method=add, it will jump to the test.jsp page, and then the page will display the information of calling the corresponding method

4. Call the delete method

  • Add hello?method=delete after the original default URL link, i.e http://localhost:8888/springmvc_ 01_ servlet_ war_ Expanded / hello?method=delete, it will jump to the test.jsp page, and then the page will display the information of calling the corresponding method

Well, that's the end of today's study on briefly reviewing the MVC architecture and the use of servlets. You are welcome to study and discuss actively. If you like, you can pay attention to Mr. snail. By the way, you can click three times. I'll see you next time. Bye!

Reference video link: [crazy God says Java] the latest tutorial of spring MVC, the IDEA version, is easy to understand

Tags: servlet Spring MVC mvc IDEA mvvm

Posted on Sun, 31 Oct 2021 13:41:50 -0400 by imurkid