[Web front end] Servlet and application



foreword

A Java Servlet is a program running on a Web server or an application server, and it acts as an intermediate layer between requests from a Web browser or other HTTP clients and the database or application on the HTTP server.

1 Introduction

Using servlets, you can collect user input from web page forms, render records from databases or other sources, and create web pages dynamically.
Java Servlet usually achieves the same effect as programs implemented using CGI (Common Gateway Interface, Common Gateway Interface). But compared to CGI, Servlet has the following advantages:
● The performance is obviously better.
● Servlets execute within the address space of the Web server. This way it doesn't need to create a separate process to handle each client request.
● Servlets are platform independent because they are written in Java.
● The Java Security Manager on the server enforces a series of restrictions to protect resources on the server computer. Therefore, the servlet is trusted.
● All functions of Java class library are available to Servlet. It can interact with applets, databases or other software through sockets and RMI mechanisms.

1.1. Servlet architecture

The following diagram shows the location of servlets in a web application.
insert image description here

1.1.1, Servlet tasks

Servlets perform the following main tasks:
● Read explicit data sent by the client (browser). This includes HTML forms on web pages, or forms from applets or custom HTTP client programs.
● Read the implicit HTTP request data sent by the client (browser). This includes cookies, media types, and compression formats that browsers understand, among other things.
● Process data and generate results. This process may require accessing a database, performing RMI or CORBA calls, invoking a Web service, or computing the corresponding response directly.
● Send explicit data (ie document) to client (browser). This document can be in a variety of formats, including text files (HTML or XML), binary files (GIF images), Excel, and more.
● Send an implicit HTTP response to the client (browser). This includes telling the browser or other client what type of document is being returned (such as HTML), setting cookies and caching parameters, and other similar tasks.

1.1.2, Servlet package

A Java Servlet is a Java class that runs on a web server with an interpreter that supports the Java Servlet Specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of Java Enterprise Edition, an extended version of the Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the corresponding versions are Java Servlet 2.5 and JSP 2.1, respectively.
A Java Servlet is created and compiled just like any other Java class. After you install the servlet packages and add them to the Classpath on your computer, you can compile the servlet with the JDK's Java compiler or any other compiler.

1.2. Servlet environment settings

1.2.1. Set up Web application server: Tomcat

There are many web application servers in the market that support Servlets. Some web application servers are free downloads, Tomcat is one of them.
Apache Tomcat is an open source software implementation of Java Servlet and JavaServer Pages technology. It can be used as an independent server for testing Servlet and can be integrated into Apache Web application server. The steps to install Tomcat on the computer are as follows:
● Download the latest version of Tomcat from http://tomcat.apache.org/.
● Once you have downloaded Tomcat, extract it to a convenient location. For example, extract to C:\apache-tomcat-5.5.29 if you are using Windows, or /usr/local/apache-tomcat-5.5.29 if you are using Linux/Unix, and create the CATALINA_HOME environment variable to point to these locations.
On Windows, Tomcat can be started by executing the following command:

 %CATALINA_HOME%\bin\startup.bat
 或者  
C:\apache-tomcat-5.5.29\bin\startup.bat

On Unix (Solaris, Linux, etc.), Tomcat can be started by executing the following command:

$CATALINA_HOME/bin/startup.sh  
或者 
/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After Tomcat starts, you can access the default applications in Tomcat by entering http://localhost:8080/ in the browser address bar. If all goes well, the following results are displayed:
insert image description here

Further information on configuring and running Tomcat can be found in the documentation for the application installation, or by visiting the Tomcat website: http://tomcat.apache.org.
On Windows, you can stop Tomcat by executing the following command:
C:\apache-tomcat-5.5.29\bin\shutdown
On Unix (Solaris, Linux, etc.), you can stop Tomcat by executing the following command:
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

1.3, Servlet life cycle

Servlet life cycle can be defined as the whole process from creation to destruction. Following is the process followed by a servlet:
● The init () method is called after the servlet is initialized.
● The Servlet calls the service() method to process the client's request.
● The destroy() method is called before the Servlet is destroyed.
● Finally, the servlet is garbage collected by the JVM's garbage collector.
Let us now discuss the lifecycle methods in detail.

1.3.1. init() method

The init method is designed to be called only once. It is called when the servlet is created for the first time, and it is not called for each subsequent user request. Therefore, it is used for one-time initialization, just like the Applet's init method.
A servlet is created the first time a user invokes the URL corresponding to that servlet, but you can also specify that the servlet be loaded when the server first starts.
When a user invokes a Servlet, a Servlet instance will be created, and each user request will generate a new thread, which will be handed over to the doGet or doPost method when appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method is defined as follows:

public void init() throws ServletException {
    
    
    // 初始化代码...
}

1.3.2, service() method

The service() method is the main method that performs the actual task. The Servlet container (that is, the Web server) calls the service() method to process the request from the client (browser) and writes the formatted response back to the client.
Every time the server receives a Servlet request, the server will spawn a new thread and invoke the service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls the doGet, doPost, doPut, doDelete, etc. methods when appropriate.
The following are the characteristics of this method:

public void service(ServletRequest request,
                    ServletResponse response)
        throws ServletException, IOException{
    
    
}

The service() method is called by the container, and the service method calls doGet, doPost, doPut, doDelete, etc. methods at the appropriate time. So, you don't need to do anything with the service() method, you just need to rewrite doGet() or doPost() according to the request type from the client.
The doGet() and doPost() methods are the most commonly used methods in each service request. The following are the characteristics of these two methods.

1.3.3, doGet() method

A GET request from a normal request to a URL, or from an HTML form with no METHOD specified, is handled by the doGet() method.

public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
        throws ServletException, IOException {
    
    
    // Servlet 代码
}

1.3.4, doPost() method

A POST request from an HTML form that specifies METHOD as POST is handled by the doPost() method.

public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException {
    
    
    // Servlet 代码
}

1.3.5, destroy() method

The destroy() method will only be called once, at the end of the Servlet life cycle. The destroy() method lets your servlet close database connections, stop background threads, write cookie lists or hit counters to disk, and perform other similar cleanup activities.
After calling the destroy() method, the servlet object is marked for garbage collection. The destroy method is defined as follows:

public void destroy() {
    
    
    // 终止化代码...
}

1.3.6, architecture diagram

The following diagram shows a typical Servlet life cycle scenario.
insert image description here
● The first HTTP request to reach the server is delegated to the Servlet container.
● The servlet container loads the servlet before calling the service() method.
• The Servlet container then processes multiple requests made by multiple threads, each thread executing the service() method of a single Servlet instance.

1.3.7. Use IDEA to write Java Web projects and deploy them to Tomcat

1. Create a new project and select Java EE
insert image description here

Configure JDK:
JDK version selection 1.8, if not, need to download

Configure Template:
Select Web application in Template
insert image description here

Configure Application server:
Application server creates a new server, select [New…], select [Tomcat Server], and fill in the local Tomcat installation directory
insert image description here
insert image description here

Configure Java EE and Servlet versions:
insert image description here
Click [Create] to complete the creation of the project

2. Configure Tomcat Server
2.1. After the project initialization is completed, select the upper right corner of the idea and configure 【Edit Configurations】
insert image description here

2.2. Add new Tomcat server configuration
insert image description here

2.3. Select [Deployment], add the project to Tomcat Server

insert image description here
insert image description here
insert image description here

3. Start Tomcat Server Configuration
insert image description here

4. Access the project
insert image description here

5. Solve the problem of Chinese garbled characters 5.1. In
the code, specify the encoding format when returning data. Windows is GBK response.setCharacterEncoding(" UTF-8
"); Set UTF-8
encoding in the AJP connector (add URIEncoding="UTF-8") Open Tomcat/conf/server.xml, find the Connector tag, add URIEncoding="UTF-8" at the end

insert image description here


6. The ContentType of response The
function of response.setContentType(MIME) is to enable the client browser to distinguish different types of data, and call different program embedding modules in the browser according to different MIMEs to process the corresponding data.
For example, a web browser judges that a file is a GIF image by MIME type. Handle json strings by MIME type.
Syntax:
response.setContentType("application/json;charset=utf-8");
supported types: application/json;charset=utf-8, text/html

Demonstration of actual effect:
insert image description here

1.3.8, Servlet application and configuration

1. Custom Servlet needs to inherit HttpServlet

import java.io.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    
    
    private String message;

    public void init() {
    
    
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        response.setContentType("text/html");
        request.getParameter("");

        // Hello
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
//        out.write( JSON.toJSONString(request) );
    }

    public void destroy() {
    
    
    }
}

2. Configure HelloServlet in Web.xml

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>com.hqsoft.demo.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

1.3.9, simulate Servlet parsing request

The process of parsing the request:
1. Simulate a complete http request and define 3 input parameters
2. Based on? Split the http request, the data at the end of the split array is the input parameter data
3, the input parameter data continues to be divided, and is divided into multiple parameter array data according to &
4, multiple parameter array data are put into the dictionary Map
5, use the dictionary to obtain data, case-sensitive

public static void main(String[] args) {
    
    
        String requestUrl = "http://localhost:8080/demo_war/hello?userName=zhangsan&age=20&sex=1";
        String[] requestUrls = requestUrl.split("\\?");
        String parameterStr =  requestUrls[1];
        String[] parameters = parameterStr.split("&");

        System.out.println( "入参的参数长度:" + parameters.length );
        System.out.println( "入参的参数信息:" + GsonUtil.gson.toJson(parameters) );

        Map request = new HashMap<>();
        for (String parameter : parameters) {
    
    
            String[] parameterA = parameter.split("=");
//            System.out.println( "name:" + parameterA[0] );
//            System.out.println( "value:" + parameterA[1] );
            request.put(parameterA[0] , parameterA[1]);
        }

        System.out.println("userName:" + request.get("userName"));
        System.out.println("age:" + request.get("age"));
        System.out.println("sex:" + request.get("sex"));

    }

Guess you like

Origin blog.csdn.net/s445320/article/details/131336089