Novice web development simple summary (four)-MVC in web application development

 

table of Contents

1. Comparison with Android/iOS development

Two JSP in web application development

Three a simple MVC in web application development

The distinction between three concepts

Four summary

Five review the previous issues 

1. New understanding of Servlet, Filter and Listener

2. New understanding of context-param and ContextLoaderListener

(1)ServletContext

(2)ApplicationContext

(3)WebApplicationContext

(4) The relationship between the three

(5) Two containers in Spring


1. Comparison with Android/iOS development

In the simple summary of the novice web development for Xiaobai (3)-a simple web development project , I simply created a web application. Because I did APP development before, I hope to compare and learn this web application development with what I am familiar with. So comparing Android/iOS application development, I found that there are some similarities:

  • 1. From the perspective of release and online, all three need to be packaged and then run in the corresponding operating environment, but the differences are:

 

  • 2. From the perspective of the development process, all three need to have page rendering -> business logic -> network communication -> data storage process, but the difference is:

Of course, the summary of this development process is relatively broad, based on the summary of current beginners. Later, as I deepen the development of web applications, I will return to see if my summary is reasonable. In addition, the two parts of business logic and data storage should still be more responsible. Learn by yourself and learn more.

Two JSP in web application development

We are a simple summary of novice web development (3) -A simple web development project in FirstServlet will write a piece of Html code to the writer of HttpServletResponse, as follows:

    writer.write(String.format("<h1> Hello Web %s ,This is a simple web!</h1>",count));

If we simply output such a sentence, we can write it in this way. There is no problem, but think about the actual development of a website, any page will have much more complicated UI, UI state and UI logic than this. So if you write in this way, it is basically impossible to implement. So there is JSP (Java Server Page).

JSP is a dynamic web page technology. The files in the project end with .jsp. These files must be placed in the webapp/ directory of the project, finally packaged into a war package, and then deployed to the server. It can respond to the request sent by the browser, and dynamically generate web pages in Html, xml or other formats according to the requested content, and finally return it to the browser. In fact, the JSP file is compiled into a servlet written in Java code before execution (the corresponding xxx_jsp.java can be found in the temporary directory of Tomcat), so a JSP corresponds to this servlet.

After the project is packaged and launched, it can be accessed through the URL path of http://localhost:8080/xxx.jsp or http://localhost:8080/Servlet (forwarded to the xxx.jsp in the Servlet).

Now let's understand this JSP through a simple example:

(1) Write relevant code for second.jsp

<%-- 用来解决中文在浏览器乱码的问题 --%>
<%@page language="java" import="java.util.*" contentType="text/html; charset=GB2312"  %>
<html>
    <head>
        <title>First JSP</title>
    </head>

    <body>
    <%-- 这是一个JSP注释示例方式 --%>
        <h1> 这是通过 JSP 渲染的页面</h1>
        <p>
    <%-- 这是一个添加Java代码示例方式 --%>
            <%
                out.println("这是通过java输出的文字,获取url中的key为");

             %>
        <%-- 行内元素标签 --%>
            <span style="color:yellowgreen">
                <%= request.getParameter("key")%>
            </span>
        </p>
         <p>
             <%-- 方法和变量的声明 --%>
             <%! int count = 1;%>
            <%
                out.println(String.format("初始化的count的值为%d",count));
            %>
        </p>
        <p>
            <%!
                int getCount(){
                    return count;
                }
            %>
        </p>
    </body>
</html>

You can see from the code that a JSP is actually an Html page, which can dynamically modify some content of the Html page. The specific JSP grammar will be studied later. A JSP generally includes four elements, see Xiaobai novice web development brief summary (5)-Four elements of JSP pages .

Now I still refer to the simple summary of web development for novices in Xiaobai (3) -a simple web development project mentioned method to allow web application projects, in fact, you can now pass http://localhost:8080/second.jsp?key= Cold medicine has come to visit the jsp, and the display interface is as follows:

In this way, we implement a Servlet through a JSP, and we can see that there is a corresponding java file of second_jsp.java in the Tomcat temporary directory.

From the source code, it is not difficult to find that the following method has completed the logic that we were writing FirstServlet.java before writing the final HTML to HttpServletResponse and returning it to the browser.

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
    throws java.io.IOException, javax.servlet.ServletException {

}

So JSP corresponds to a Servlet, which automatically compiles .jsp files into .java files. The difference with Servlet is that JSP embeds dynamic output files in HTML, while Servlet outputs HTML in Java code.

Usually when we visit a website, we rarely see the url method of http://localhost:8080/second.jsp , so we also need to map second.jsp to a url, of course, based on the previous simple For web application examples, you can map second.jsp to a url by writing a SeondSerlvet.java method (I understand this is the logic of mapping Controller to .jsp in the Spring project).

(2) Add SecondServlet.java to map second.jsp into a url


@WebServlet(urlPatterns = "/second")
public class SecondServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/second.jsp").forward(req, resp);
    }
}

After starting the project, you can directly access the servlet.jsp page through http://localhost:8080/second?key=success . The relevant code has been uploaded to githut, the address is: https://github.com/wenjing-bonnie/build-spring.git

Three a simple MVC in web application development

MVC: Model-View-Controller. Model mainly refers to some business models. View is the interface that users can see. Controller is to initialize View and Model. Use Model to get the data of rendering View. Separate the code of Model and View. Then in a web application development, this How is the three-layer manifested?

Through the simple examples of the previous few times, you can also compare: the use of Servlet and JSP are both used to write business logic:

But Servlet is suitable for writing Java code and processing complex business logic, but it is not conducive to outputting complex HTML; while JSP is suitable for writing HTML and can dynamically insert content, but it is not suitable for complex Java code. Then we can actually hand the complex business logic to the Java code, and hand the final displayed result to the JSP.

Use a simple example to see how these two work together: simulate a user's shopping cart on a shopping website to display the book name and price (in actual development, it is more complicated than the following logic, only simulation).

  • 1. Define the entity classes of books and users separately (in actual development, this should be a table corresponding to the database)
public class Book {
    public String name;
    public float price;
}

public class Customer {
    public long memberId;
    public String memberName;
}
  •  2. Define BookController to find out the price of the book based on the book name
public class BookController {

    private SqlDataBase sqlDataBase;

    /**
     * 根据用户购买的图片获取图书价格,当然在实际的处理要比这个复杂
     *
     * @param name
     * @return
     */
    public Book getBook(String name) {
        Book book = new Book();
        //模拟查询数据库
        sqlDataBase.query(name);
        book.name = name;
        book.price = 39;
        return book;
    }
}
  • 3. Define the CustomerController class to query the user's name based on the user's id
public class CustomerController {
    private SqlDataBase sqlDataBase;

    /**
     * 根据用户id获取用户的名字
     *
     * @param memberId
     * @return
     */
    public Customer getCustomer(long memberId) {
        Customer customer = new Customer();
        //模拟查询数据库
        sqlDataBase.query(memberId);
        customer.memberId = memberId;
        customer.memberName = "小刘";
        return customer;
    }
}
  • 4. Get the user's name and the price of the book purchased by the user in BuyServlet, and then hand the final result to buy.jsp for processing

Instantiate BookController and CustomerController in BuyServlet, then get Book and Customer, and then hand it over to buy.jsp to render the page.

@WebServlet(urlPatterns = "/buy")
public class BuyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //模拟从数据库中根据"name"找到对应的Book实体对象
        String name = req.getParameter("name");
        BookController bookController = new BookController();
        Book book = bookController.getBook(name);
        //模拟从数据库中得到Customer
        CustomerController customerController = new CustomerController();
        Customer customer = customerController.getCustomer(122);
        req.setAttribute("book", book);
        req.setAttribute("customer", customer);
        //交给jsp来动态渲染
        req.getRequestDispatcher("/buy.jsp").forward(req, resp);
    }
}

From buy.jsp, we can see that there is no need to care about how Book and Customer are obtained, but only need to render the UI based on the model object given by BuyServlet.

<%--
  Created by IntelliJ IDEA.
  User: j1
  Date: 2021/2/10
  Time: 11:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.wj.mvc.Customer" contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.wj.mvc.Book" %>
<%
    Customer customer = (Customer) request.getAttribute("customer");
    Book book = (Book) request.getAttribute("book");
%>
<html>
<head>
    <title>Mall</title>
</head>
<body>

    <h1>模拟某网站购物</h1>
    <p>
        亲爱的 <span style="color:red;size: A3;"><%= customer.memberName%></span> 顾客
    </p>
    <p>
        购买的图书为:<span style="color: yellowgreen;size: A3">《<%= book.name%>》</span>
        ,需要付款 <span style="color: yellowgreen;size: A3"><%= book.price%></span> 元
    </p>

</body>
</html>

Run the project, enter http://localhost:8080/buy?name=HeadFirst design mode in the browser to see the result:

As can be seen from this simple example, in fact, buy.jsp is a display of View, Book and Customer are Model objects, and BuyServlet is processing business logic, owning Model and View, and is responsible for obtaining the Model, and handing the Model to the View for processing , And combines the advantages of both Servlet and JSP, no matter in processing business logic or page rendering, it seems more convenient than using either side alone.

The relevant code has been uploaded to github: https://github.com/wenjing-bonnie/build-spring.git   corresponds to the relevant code under the package com.wj.mvc.

The distinction between three concepts

In fact, in the above example, it is still not very flexible. Every time you write a page, you must correspond to a class, and you need to inherit HttpServlet. Then there is the Spring MVC framework behind.

1. What is Spring

Spring is a container framework. The core is to provide an IoC (Invsersion of Control) container that can manage JavaBean components and maintain the relationship between components, including component life cycle management, configuration, and assembly.

Supplement: The container can be understood as providing the necessary software environment for the operation of a specific component. For example, Tomcat is a Servlet container, which provides an environment for running Servlet; Docker is a Linux process container, which provides an environment for running a specific Lunix process, so Spring is a JavaBean component container.

The example we mentioned in the second part has the following drawbacks:

(1) When using each Controller in BuyServlet, you need to know how to create it;

(2) If there are dependencies between Controllers, the instances inside cannot be shared;

(3) Each of the above processes needs to be controlled by the developer.

And Spring is to solve this problem. The creation of components does not need to be created by the developer, but directly handed over to the IoC container. Developers only need to configure the components and the dependencies between the components through the xml file; and like the second mentioned above This problem has also been avoided. As long as in one configuration, if there is a dependency between two classes, it can be used directly in the other class. The IoC container is responsible for managing the entire life cycle of the component.

2. What is Spring MVC

The MVC framework of the web layer replaces Servlet. Through DispatcherServlet to hand over the request to different modules for processing. It can be seen that Struts2 (essentially equivalent to a Servlet) + Spring integration.

3. What is Spring Boot

The microservice framework simplifies the creation, operation, debugging, and deployment of Spring applications. You can only focus on Spring development without paying too much attention to XML configuration.

Four summary

Because I was doing mobile development before, after two weeks, I can finally compare the related content of mobile development and understand the entire development process of web applications. So we will continue to study the creation process of a Spring MVC project in the future:

  • 1. The web application development is finally packaged into a war package and placed on the server where Tomcat has been installed;
  • 2. Tomcat is actually an environment of the war package;
  • 3. The so-called project is successfully launched, and the Tomcat server must be started at the end, then the content of the war package will be read, and then the web address can be entered in the browser to open the corresponding page;
  • 4. Servlet can use Java code to focus on business logic; then pass the Model to JSP, and then JSP to render the page;
  • 5. Spring is an IoC container used to manage the life cycle of JavaBean components.

Five review the previous issues 

After reviewing the simple summary of the novice web development for Xiaobai (2)-what is web.xml  , I found that I have some new understanding of the vague understanding before:

1. New understanding of Servlet, Filter and Listener

This article is the first document that I came into contact with when I first learned about web application development projects. At that time, I didn't figure out why it was necessary to configure these contents. But to summarize it now: a web application development usually includes three parts:

  • (1) Processing dynamic business components: Servlet, Filter, Listener

So some Filter, Listener and Servlet are configured in the web.xml file

  • (2) View components: such as JSP

Java code is used to implement the responsible business logic, and finally the page is dynamically rendered through req.getRequestDispatcher("/buy.jsp").forward(req, resp);. This JSP is somewhat similar to the .wxml file of WeChat applet

  • (3) Static resource files: such as CSS, JS, etc.

Usually, when a web application is deployed in a production environment, it will use Nginx and Tomcat server configuration. As a gateway, Nginx acts as a reverse proxy and static server, which can efficiently process static files and only hand over dynamic requests to the Tomcat server (so Tomcat servers usually run business systems). At the same time, you can also put Https, firewall, speed limit, anti-crawler and other functions into Nginx, so that webapp can focus more on business logic.

2. New understanding of context-param and ContextLoaderListener

(1)ServletContext

<context-param> configures the parameters of ServletContext, and ServletContext is the Servlet context. The Servlet container creates a ServletContext object for each application, which is globally unique. This object is shared by all Servlets and used to transfer data between Servlets. .

(2)ApplicationContext

ContextLoaderListener monitors the process of Tomcat publishing web applications, and automatically assembles ApplicationContext configuration information in this process. And this ApplicationContext is Spring's core interface for implementing IoC. Through this ApplicationContext, Spring's IoC container can be obtained, and then all Java Bean instances in the container can be obtained. Multiple ApplicationContexts are allowed in Spring.

Common ApplicationContext implementation classes are:

(1) ClassPathXmlApplicationContext: Load the corresponding configuration file under the class path

    ApplicationContext context = new ClassPathXmlApplicationContext("config/application-context.xml");

(2) FileSystemXmlApplicationContext: Load the configuration file under any path of the disk, you must have access rights

    ApplicationContext ctx = new FileSystemXmlApplicationContext("/Users/wj/Documents/java/pc/build-spring/src/main/resources/config/application-context.xml")

Without a drive letter, it is the working path of the project, that is, the root directory of the project; if there is a drive letter, it is the absolute path of the file 

(3) WebApplicationContext: specifically to load configuration files for web applications, there are usually two implementation classes:

  • 1) XmlWebApplicationContext: read the configured JavaBean through an XML file;
  • 2) AnnotationConfigApplicationContext: Read the configured JavaBean by reading the java class corresponding to @Configuration and @Bean

With the IoC container, the ApplicationContext can obtain the Bean in two ways:

(1) Through the type of JavaBean, the most commonly used way

        ApplicationContext context = new ClassPathXmlApplicationContext("config/application-context.xml");
        RegisterService service = context.getBean(RegisterService.class);

(2) Through the ID of JavaBean

        ApplicationContext context = new ClassPathXmlApplicationContext("config/application-context.xml");
       // 该ID为在xml文件中配置的id;
        RegisterService service = (RegisterService)context.getBean("registerService");

(3)WebApplicationContext

The context of the web application is a sub-interface of ApplicationContext. Only on the basis of ApplicationContext, a reference to ServletContext is added, and ServletContext can be accessed through getServletContext() in WebApplicationContext.

(4) The relationship between the three

 The relationship between integrated ServletContext, ApplicationContext, and WebApplicationContext is:

(1) WebApplicationContext is a sub-interface of ApplicationContext, which contains ServletContext;

(2) When Tomcat is started, it must first create a ServletContext as a Servlet container

(3) In the process of monitoring Tomcat to publish web applications, a WebApplicationContext will be created (this time is the xml file configured in the contextConfigLocation), which is used to obtain various JavaBeans configured in the IoC container;

(4) ServletContext is included in WebApplicationContext, which can be accessed through getServletContext();

(5) WebApplicationContext can also be obtained in ServletContext, because WebApplicationContext has been placed in ServletContext as an attribute value, and the corresponding key is WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE

(5) Two containers in Spring

In addition, Spring removes the ApplicationContext IoC container, and there is also a BeanFactory container. The difference between the two is that BeanFactory will create Beans on demand, and will create Beans only when the Bean is first obtained; and ApplicationContext will create all Beans at once. In fact, ApplicationContext is inherited from BeanFactory.

Let’s learn about Spring’s IoC container in the next article: A simple summary of web development for novices (6)-Spring’s IoC container

 

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/113767898