Novice web development simple summary (three)-a simple web development project

table of Contents

I. Introduction

Two web application development

1. What is web application development

2. A simple web application

3. The actual web application

Three breakpoint debugging of web application development

Four summary


I. Introduction

After a brief summary of web development by Xiaobai novice web development (1)-What is Tomcat and a brief summary of web development by Xiaobai novice web development (2)-What is web.xml , I have a little understanding of a web development, a development process should probably be Looks like this:

  • 1. A web project is developed and finally the project code (front-end page display + business logic) is packaged into a war package through maven;
  • 2. Install Tomcat on the server, then there will be a webapps folder in the installation directory, then we will put the war package packaged in the first step into this directory. (It can also be seen from the naming method of webapps that this Tomcat can start multiple web applications);
  • 3. Enter the bin directory, run .startup.sh, start Tomcat, then the web.xml configuration file in the war package will be read, and follow the simple summary of the novice web development by Xiaobai (2) -what is web.xml Instantiate the class inside, then we can access the web application by entering the url in the browser.

The above three points are summarized based on an operation method on my local computer. The actual operation process in a website development process will be studied later, but I think it should be almost like this. So for later learning a web development, I think it is necessary to learn the relationship between Spring, Spring MVC, Tomcat, a request comes, how to complete a request?

Two web application development

1. What is web application development

Web application development generally uses B/S architecture. From the perspective of development, I think that the development of a web application is the same as the development of an APP. It can be divided into these parts: web page-related business logic + network communication + functions that the network provides to the business layer . For the user, only a browser is required, and the relevant business logic and data of the web application exist on the server side. The browser communicates with the server through the Http protocol, obtains the content of the web page, and displays it to the user through the browser.

The role of the browser in the whole process:

(1) Establish a TCP connection with the server;

(2) Send an Http request, in which GET/POST will be marked;

(3) Receive the Http response and display the content returned by the server in the browser.

Both the request and response include Http Header and Http Body, and the response body returns corresponding web page data according to the set Content-Type (such as text/html, it will return <html></html>), and the browser will display this information That's it. The first resource obtained by the browser is these Html web pages. If there are resources such as JavaScript, CSS, and images, the browser will send a request to the server again according to the corresponding resource url.

The role of the server in the whole process:

(1) Establish a TCP connection with the browser;

(2) Identify Http requests, receive and process Http requests;

(3) Return the processed Http request to the browser.

From the division of roles, it can be seen that the server has already processed and parsed Http requests and other network communication work, the browser is responsible for sending and receiving Http requests, and the web application only needs to be placed on the web server. In Java EE, HttpServlet is provided to process Http requests, so as long as the server implements HttpServlet, network communication can be realized.

2. A simple web application

I think HttpSerlvet can be understood as a class for processing Http requests sent by the client, which has two methods:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
protected void doPost(HttpServletRequest req, HttpServletResponse resp)

The parameters HttpServletRequest req, HttpServletResponse resp represent the request and response. When using this HttpSerlvet, you don’t need to care about how to interact with TCP, and you don’t need to parse Http. For example, in the doGet() method, you only need to: receive the request parameters sent by the browser from req, and complete the business logic in this method. And the operation of reading and writing the database, and finally write the result to the resp, then the browser can receive the relevant data, and the logic of the request and response has been encapsulated in the res and resp.

Through this HttpSerlvet to complete a simple example of web application development:

(1) Create a Maven project through IDEA

(2) Configure pom.xml and introduce Servlet

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

Note here that the dependency should be introduced as <provided> (ie setting <scope>provided</scope>), so that it will only be used during compilation, and will not be packaged into the .war package at the end, because Tomcat will be used later The corresponding Servlet API already exists in the server. 

 (3) The configuration package type is .war, and the configuration is finally packaged into the name of .war

    <packaging>war</packaging>
    <build>
        <finalName>builder-spring</finalName>
    </build>

(4) Create a FirstServlet java file in the java directory, and write a simple display sentence.

@WebServlet(urlPatterns = "/")
public class FirstServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.write("<h1> Hello Web ,This is a simple web!</h1>");
        //强制输出
        writer.flush();
    }
}

Of course, you can also getOutputStream()get the write stream. Another thing to note is that flush() must be called after the writing is completed, otherwise the data cannot be returned to the browser in time, and close() is a closed TCP connection, and this method cannot be called.

(5) Create the web application description file web.xml in the main/webapp/WEB-INF directory of the project project

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>build spring</display-name>
</web-app>

(6) Package through the maven that comes with IDEA, execute clean->compile->package in turn, and then generate the build-spring.war package in the target directory

(7) Copy the build-spring.war package to the Tomcat installation directory webapps, return to the bin directory, run .startup.sh, and display in the terminal command window:

MacBook-Pro:bin j1$ ./startup.sh 
Using CATALINA_BASE:   /Users/j1/Documents/java/apache-tomcat-9.0.41
Using CATALINA_HOME:   /Users/j1/Documents/java/apache-tomcat-9.0.41
Using CATALINA_TMPDIR: /Users/j1/Documents/java/apache-tomcat-9.0.41/temp
Using JRE_HOME:        /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
Using CLASSPATH:       /Users/j1/Documents/java/apache-tomcat-9.0.41/bin/bootstrap.jar:/Users/j1/Documents/java/apache-tomcat-9.0.41/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

(8) Enter http://localhost:8080/builder-spring/ in the browser , where /builder-spring/ is the name of the war package, and you can see the following interface

Of course, you can also  add parameters through http://localhost:8080/builder-spring/?count=2 , then you can read directly through HttpServletRequest in FirstServlet:

@WebServlet(urlPatterns = "/")
public class FirstServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        String count = req.getParameter("count");
        PrintWriter writer = resp.getWriter();
        writer.write(String.format("<h1> Hello Web %s ,This is a simple web!</h1>",count));
        //强制输出
        writer.flush();
    }

Visit in the browser as follows: 

Through the above steps, a simple web application was successfully created. When the browser visits " http://localhost:8080/builder-spring/ ", it will send a request, and then there will be Tomcat (a simple summary of the novice web development of the previous novice (1)-what is Tomcat is also mentioned Tomcat is actually a Servlet container) will hand the request to FirstServlet for processing (@WebServlet(urlPatterns = "/") provides the mapping relationship).

In addition, the composition of this url is actually the <finalName> we configured in pom.xml, plus @WebServlet(urlPatterns = "/") in FirstServlet.

The above code has been uploaded to github, the github address is: https://github.com/wenjing-bonnie/build-spring.git

3. The actual web application

Of course, in a web application, there are many Servlets, each Servlet will be mapped to a path. Therefore, in the development of a complete web application, the business logic related to the web page can actually be subdivided into several processes:

  • (1) Different Servlets corresponding to different path mappings;

When each Servlet processes business logic, it can actually be subdivided into processes:

1) Read request parameters from HttpServletRequest;

2) Processing complex business logic: there must be a common operation class for reading and writing the database, each table in the database must correspond to some encapsulation classes, and there must be encapsulation classes for the operations of these tables, more in this Servlet It may involve the operation of multiple database tables, which means that the operation classes of multiple tables need to be introduced;

3) Write the response data to HttpServletResponse, and the response data can be seen to be some data for the browser to display (in the example mentioned above, the response data may only be used to display a string, but in actual development there will be more More page-related rendering, such as jsp);

Obviously in this process there will be many instantiation and loading of class instances, as well as the management of the life cycle of these class instances, and can also be abstracted into a Model-View-Controller design pattern in a Servlet.

  • (2) The web server forwards different paths to the corresponding Servlet according to the path mapping rules. This forwarding function is usually completed by the server Dispatcher.

Then the network communication and the functions that the network provides to the business layer are completed by Tomcat. Compared with the previous simple summary of web development in Xiaobai novices (1)-What is Tomcat and a simple summary of web development for Xiaobai novices (2)-What is web.xml , these processes seem to have specific correspondence:

  • (1) Tomcat is a Servlet container, used to instantiate Servlet to process requests and responses. The Tomcat Connector is responsible for establishing a connection with the browser, receiving the request sent by the browser and returning the response to the browser;
  • (2) The Engine in the Container in Tomcat is used to instantiate the Servlet, manage the life cycle of the Servlet, and complete the underlying network communication;
  • (3) DispatcherSerlvet is registered in web.xml to map the request sent by the browser to the processing class of the corresponding path.

Now it seems that some knowledge points for web application development are beginning to become clear.

Three breakpoint debugging of web application development

From the above simple example, we can see that a web application development is actually writing a Servlet to process the Http request sent by the browser. Of course, we need to package the final Servlet into a war package according to the established rules, and load the war package through Tomcat. , And run these servlets.

In the sixth and seventh steps mentioned above in a simple web application example, we need to package the war package through IDEA, and start the war package through the locally installed Tomcat. What about breakpoint debugging? In fact, we can Tomcat is also a java program. To start Tomcat through .startup.sh is actually to start the JVM and execute Tomcat's main() method, and initialize the Servlet after loading the war package to provide services to the browser. In fact, we can complete a Tomcat startup web project in the form of code.

(1) Still the above project code, we will replace javax.servlet with Tomcat related dependencies:

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>${tomcat.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>${tomcat.version}</version>
        </dependency>

(2) Increase the main() method of Tomcat instantiation


public class FirstServletTest {
    public static void main(String[] args) throws LifecycleException {
        //创建Tomcat
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(Integer.getInteger("port", 8080));
        tomcat.getConnector();
        //创建webapp
        Context context = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());
        WebResourceRoot resources = new StandardRoot(context);
        DirResourceSet set = new DirResourceSet(resources, "/WEB-INF/classes", new File("target/classes").getAbsolutePath(), "/");
        resources.addPreResources(set);
        context.setResources(resources);
        //启动Tomcat
        tomcat.start();
        tomcat.getServer().await();
    }
}

(3) Run the main() method, and then it will be displayed below in IDEA, indicating that the embedded Tomcat has been successfully started, and Tomcat will automatically place this project in the root directory, which can be directly accessed through http://localhost:8080/ ?count=2 to access the corresponding Servlet

二月 08, 2021 2:00:25 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-nio-8080"]
二月 08, 2021 2:00:25 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Tomcat]
二月 08, 2021 2:00:25 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet engine: [Apache Tomcat/9.0.36]
二月 08, 2021 2:00:25 下午 org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
信息: No global web.xml found
二月 08, 2021 2:00:27 下午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
二月 08, 2021 2:00:27 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-nio-8080"]

In this way, a project can be easily debugged with a breakpoint by running the main() of FirstServletTest. But in an actual web application development, I don't know if it is breakpoint debugging in this way, and I need to study and research myself.

The code github address is: https://github.com/wenjing-bonnie/build-spring.git

Four summary

Through this simple example of web application development, compare the previous simple summary of web development by Xiaobai novices (1)-What is Tomcat and simple summary of web development for Xiaobai novices (2)-What is a summary of web.xml , simple in Summarize what is clear now:

  • 1. A web application development project is packaged into a war package through maven and runs on a web server that supports Servlet;
  • 2. Tomcat is a web server that supports Servlet. Every time a web application service goes online, you should put the war package in the relevant directory of Tomcat installed on the server, and start Tomcat;
  • 3. After Tomcat is started, it will read the web.xml file of the war package, and then instantiate the corresponding classes in it;
  • 4. When a browser sends a request, it will first establish a TCP connection with the web server, and the browser sends the request;
  • 5. After Tomcat receives the request, there will be DispatcherServlet matching the corresponding processing class according to the path;
  • 6. The response after processing is sent to the browser, and the browser is responsible for displaying the data
  • 7. HttpServlet does not need to care about the underlying TCP and other related network logic. It only needs to obtain the request parameters from the HttpServletRequest, and after the business logic, write the processed data to the HttpServletResponse.

In addition, record several knowledge points about Servlet: When writing response data to HttpServletResponse, you can specify whether the browser is to redirect or forward

  • 1. Redirect

When the browser requests a url, the server will tell the browser that the address has changed after processing the data and returning it to the browser, and the browser needs to resend the request. Redirection is achieved through the following code:

  String redirectToUrl = "/xxxx";
   // 发送重定向响应:
   resp.sendRedirect(redirectToUrl);

The browser received the following response:

HTTP/1.1 302 Found
Location: /xxxx

According to the URL returned by Location, a new request will be sent again. Then you see two requests in the browser. Of course, redirection is divided into temporary redirection (302 response) and permanent redirection (301 response). The difference between the two is permanent redirection. The browser will replace the URL sent by Location, and the next time the previous URL is requested, the URL corresponding to Location will be sent directly. Pass in the code

// HttpServletResponse.SC_MOVED_PERMANENTLY:301
//HttpServletResponse.SC_FOUND:302
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); 
resp.setHeader("Location", "/xxxx");
  • 2. Forward

Forwarding refers to internal forwarding. When a Servlet processes a request sent by a browser, it does not process it by itself, but forwards it to another Servlet for processing. Implemented in the code:

req.getRequestDispatcher("/xxxx").forward(req, resp);

Subsequent request processing is actually handed over to the servlet corresponding to "/xxxx" for processing.

Compared with redirection, this forwarding is only done internally by the server. For the browser, only one request is sent, without any processing itself. There is always only one URL in the browser.

Every day has been fulfilling these days, come on! ! ! ! ! Next time, I will look at the simple summary of Xiaobai novice web development (four)-MVC in web application development

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/113752940
Recommended